<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><div id="myscoll"></div><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>SpringBoot使用ShardingSphere | XiaoFei🥝</title><meta name="keywords" content="SpringBoot使用ShardingSphere"><meta name="author" content="XiaoFei🥝"><meta name="copyright" content="XiaoFei🥝"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="SpringBoot使用ShardingSphere">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot使用ShardingSphere">
<meta property="og:url" content="https://www.naste.top:1024/posts/2343814370.html">
<meta property="og:site_name" content="XiaoFei🥝">
<meta property="og:description" content="SpringBoot使用ShardingSphere">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://www.naste.top:9000/webp/1675912183.webp">
<meta property="article:published_time" content="2023-08-17T09:35:01.000Z">
<meta property="article:modified_time" content="2024-04-26T09:52:18.225Z">
<meta property="article:author" content="XiaoFei🥝">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="MySQL">
<meta property="article:tag" content="SpringBoot">
<meta property="article:tag" content="ShardingSphere">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://www.naste.top:9000/webp/1675912183.webp"><link rel="shortcut icon" href="/"><link rel="canonical" href="https://www.naste.top:1024/posts/2343814370"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/6.0.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.json","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":230},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdnjs.cloudflare.com/ajax/libs/flickr-justified-gallery/2.1.2/fjGallery.min.js',
      css: 'https://cdnjs.cloudflare.com/ajax/libs/flickr-justified-gallery/2.1.2/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'SpringBoot使用ShardingSphere',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-04-26 17:52:18'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://cdn1.tianli0.top/npm/element-ui@2.15.6/packages/theme-chalk/lib/index.css"><style id="themeColor"></style><style id="rightSide"></style><style id="transPercent"></style><style id="blurNum"></style><style id="settingStyle"></style><span id="fps"></span><style id="defineBg"></style><style id="menu_shadow"></style><svg aria-hidden="true" style="position:absolute; overflow:hidden; width:0; height:0"><symbol id="icon-sun" viewBox="0 0 1024 1024"><path d="M960 512l-128 128v192h-192l-128 128-128-128H192v-192l-128-128 128-128V192h192l128-128 128 128h192v192z" fill="#FFD878" p-id="8420"></path><path d="M736 512a224 224 0 1 0-448 0 224 224 0 1 0 448 0z" fill="#FFE4A9" p-id="8421"></path><path d="M512 109.248L626.752 224H800v173.248L914.752 512 800 626.752V800h-173.248L512 914.752 397.248 800H224v-173.248L109.248 512 224 397.248V224h173.248L512 109.248M512 64l-128 128H192v192l-128 128 128 128v192h192l128 128 128-128h192v-192l128-128-128-128V192h-192l-128-128z" fill="#4D5152" p-id="8422"></path><path d="M512 320c105.888 0 192 86.112 192 192s-86.112 192-192 192-192-86.112-192-192 86.112-192 192-192m0-32a224 224 0 1 0 0 448 224 224 0 0 0 0-448z" fill="#4D5152" p-id="8423"></path></symbol><symbol id="icon-moon" viewBox="0 0 1024 1024"><path d="M611.370667 167.082667a445.013333 445.013333 0 0 1-38.4 161.834666 477.824 477.824 0 0 1-244.736 244.394667 445.141333 445.141333 0 0 1-161.109334 38.058667 85.077333 85.077333 0 0 0-65.066666 135.722666A462.08 462.08 0 1 0 747.093333 102.058667a85.077333 85.077333 0 0 0-135.722666 65.024z" fill="#FFB531" p-id="11345"></path><path d="M329.728 274.133333l35.157333-35.157333a21.333333 21.333333 0 1 0-30.165333-30.165333l-35.157333 35.157333-35.114667-35.157333a21.333333 21.333333 0 0 0-30.165333 30.165333l35.114666 35.157333-35.114666 35.157334a21.333333 21.333333 0 1 0 30.165333 30.165333l35.114667-35.157333 35.157333 35.157333a21.333333 21.333333 0 1 0 30.165333-30.165333z" fill="#030835" p-id="11346"></path></symbol></svg><!-- hexo injector head_end start --><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiperstyle.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/tag_plugins.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/carousel-touch.js"></script><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/animate.min.css" media="print" onload="this.media='screen'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.css" media="print" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="XiaoFei🥝" type="application/atom+xml">
</head><body><div id="loading-box" onclick="document.getElementById(&quot;loading-box&quot;).classList.add(&quot;loaded&quot;)"><div class="loading-bg"><div class="loading-img"></div><div class="loading-image-dot"></div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://www.naste.top:9000/images/cat.jpg" onerror="onerror=null;src='/assets/r1.jpg'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">149</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">99</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">46</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-home"></use></svg><span class="menu_word" style="font-size:17px"> 首页</span></a></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--article"></use></svg><span class="menu_word" style="font-size:17px"> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-guidang1">                   </use></svg><span class="menu_word" style="font-size:17px"> 归档</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-sekuaibiaoqian">                   </use></svg><span class="menu_word" style="font-size:17px"> 标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-fenlei">                   </use></svg><span class="menu_word" style="font-size:17px"> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pinweishenghuo"></use></svg><span class="menu_word" style="font-size:17px"> 休闲</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/life/music/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-yinle">                   </use></svg><span class="menu_word" style="font-size:17px"> 八音盒</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/movies/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-dianying1">                   </use></svg><span class="menu_word" style="font-size:17px"> 影院</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/games/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-youxishoubing">                   </use></svg><span class="menu_word" style="font-size:17px"> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xiangzi"></use></svg><span class="menu_word" style="font-size:17px"> 八宝箱</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/box/gallery/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-tubiaozhizuomoban">                   </use></svg><span class="menu_word" style="font-size:17px"> 画廊</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/animation/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-nvwumao">                   </use></svg><span class="menu_word" style="font-size:17px"> 动画</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/nav/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-zhifengche">                   </use></svg><span class="menu_word" style="font-size:17px"> 网址导航</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shejiaoxinxi"></use></svg><span class="menu_word" style="font-size:17px"> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/social/fcircle/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pengyouquan">                   </use></svg><span class="menu_word" style="font-size:17px"> 朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/comments/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-liuyan">                   </use></svg><span class="menu_word" style="font-size:17px"> 留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/social/link/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-lianjie">                   </use></svg><span class="menu_word" style="font-size:17px"> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-wangye"></use></svg><span class="menu_word" style="font-size:17px"> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/site/census/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--tongjibiao">                   </use></svg><span class="menu_word" style="font-size:17px"> 网站统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/echarts/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shujutongji1">                   </use></svg><span class="menu_word" style="font-size:17px"> 文章统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/time/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xianxingshalou">                   </use></svg><span class="menu_word" style="font-size:17px"> 旧时光</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-maoliang"></use></svg><span class="menu_word" style="font-size:17px"> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/personal/bb/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-qunliaotian">                   </use></svg><span class="menu_word" style="font-size:17px"> 唠叨</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/love/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-love-sign">                   </use></svg><span class="menu_word" style="font-size:17px"> 恋爱小屋</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/about/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 关于</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/encryption/%E6%9C%BA%E5%9C%BA/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 机场</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">XiaoFei🥝</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-home"></use></svg><span class="menu_word" style="font-size:17px"> 首页</span></a></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--article"></use></svg><span class="menu_word" style="font-size:17px"> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-guidang1">                   </use></svg><span class="menu_word" style="font-size:17px"> 归档</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-sekuaibiaoqian">                   </use></svg><span class="menu_word" style="font-size:17px"> 标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-fenlei">                   </use></svg><span class="menu_word" style="font-size:17px"> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pinweishenghuo"></use></svg><span class="menu_word" style="font-size:17px"> 休闲</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/life/music/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-yinle">                   </use></svg><span class="menu_word" style="font-size:17px"> 八音盒</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/movies/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-dianying1">                   </use></svg><span class="menu_word" style="font-size:17px"> 影院</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/games/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-youxishoubing">                   </use></svg><span class="menu_word" style="font-size:17px"> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xiangzi"></use></svg><span class="menu_word" style="font-size:17px"> 八宝箱</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/box/gallery/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-tubiaozhizuomoban">                   </use></svg><span class="menu_word" style="font-size:17px"> 画廊</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/animation/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-nvwumao">                   </use></svg><span class="menu_word" style="font-size:17px"> 动画</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/nav/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-zhifengche">                   </use></svg><span class="menu_word" style="font-size:17px"> 网址导航</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shejiaoxinxi"></use></svg><span class="menu_word" style="font-size:17px"> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/social/fcircle/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pengyouquan">                   </use></svg><span class="menu_word" style="font-size:17px"> 朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/comments/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-liuyan">                   </use></svg><span class="menu_word" style="font-size:17px"> 留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/social/link/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-lianjie">                   </use></svg><span class="menu_word" style="font-size:17px"> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-wangye"></use></svg><span class="menu_word" style="font-size:17px"> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/site/census/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--tongjibiao">                   </use></svg><span class="menu_word" style="font-size:17px"> 网站统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/echarts/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shujutongji1">                   </use></svg><span class="menu_word" style="font-size:17px"> 文章统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/time/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xianxingshalou">                   </use></svg><span class="menu_word" style="font-size:17px"> 旧时光</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-maoliang"></use></svg><span class="menu_word" style="font-size:17px"> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/personal/bb/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-qunliaotian">                   </use></svg><span class="menu_word" style="font-size:17px"> 唠叨</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/love/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-love-sign">                   </use></svg><span class="menu_word" style="font-size:17px"> 恋爱小屋</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/about/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 关于</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/encryption/%E6%9C%BA%E5%9C%BA/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 机场</span></a></li></ul></div></div><center id="name-container"><a id="page-name" href="javascript:scrollToTop()">PAGE_NAME</a></center><div id="nav-right"><div id="search-button"><a class="search faa-parent animated-hover" title="检索站内任何你想要的信息"><svg class="faa-tada icon" style="height:24px;width:24px;fill:currentColor;position:relative;top:6px" aria-hidden="true"><use xlink:href="#icon-valentine_-search-love-find-heart"></use></svg><span> 搜索</span></a></div><a class="meihua faa-parent animated-hover" onclick="toggleWinbox()" title="美化设置-自定义你的风格" id="meihua-button"><svg class="faa-tada icon" style="height:26px;width:26px;fill:currentColor;position:relative;top:8px" aria-hidden="true"><use xlink:href="#icon-tupian1"></use></svg></a><a class="sun_moon faa-parent animated-hover" onclick="switchNightMode()" title="浅色和深色模式转换" id="nightmode-button"><svg class="faa-tada" style="height:25px;width:25px;fill:currentColor;position:relative;top:7px" viewBox="0 0 1024 1024"><use id="modeicon" xlink:href="#icon-moon">       </use></svg></a><div id="toggle-menu"><a><i class="fas fa-bars fa-fw"></i></a></div></div></div></nav><div id="post-info"><h1 class="post-title">SpringBoot使用ShardingSphere</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><svg class="meta_icon post-meta-icon" style="width:30px;height:30px;position:relative;top:10px"><use xlink:href="#icon-rili"></use></svg><span class="post-meta-label">发表于 </span><time class="post-meta-date-created" datetime="2023-08-17T09:35:01.000Z" title="发表于 2023-08-17 17:35:01">2023-08-17</time><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-gengxin1"></use></svg><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-04-26T09:52:18.225Z" title="更新于 2024-04-26 17:52:18">2024-04-26</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-biaoqian"></use></svg><a class="post-meta-categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right post-meta-separator"></i><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-biaoqian"></use></svg><a class="post-meta-categories" href="/categories/Java/SpringBoot/">SpringBoot</a><i class="fas fa-angle-right post-meta-separator"></i><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-biaoqian"></use></svg><a class="post-meta-categories" href="/categories/Java/SpringBoot/%E7%AC%AC%E4%B8%89%E6%96%B9SDK%E6%95%B4%E5%90%88/">第三方SDK整合</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><svg class="meta_icon post-meta-icon" style="width:25px;height:25px;position:relative;top:8px"><use xlink:href="#icon-charuword"></use></svg><span class="post-meta-label">字数总计:</span><span class="word-count">1.1w</span><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:20px;height:20px;position:relative;top:5px"><use xlink:href="#icon-shizhong"></use></svg><span class="post-meta-label">阅读时长:</span><span>47分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="SpringBoot使用ShardingSphere"><svg class="meta_icon post-meta-icon" style="width:25px;height:25px;position:relative;top:5px"><use xlink:href="#icon-eye"></use></svg><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><section class="main-hero-waves-area waves-area"><svg class="waves-svg" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto"><defs><path id="gentle-wave" d="M -160 44 c 30 0 58 -18 88 -18 s 58 18 88 18 s 58 -18 88 -18 s 58 18 88 18 v 44 h -352 Z"></path></defs><g class="parallax"><use href="#gentle-wave" x="48" y="0"></use><use href="#gentle-wave" x="48" y="3"></use><use href="#gentle-wave" x="48" y="5"></use><use href="#gentle-wave" x="48" y="7"></use></g></svg></section></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="目录"><a href="#目录" class="headerlink" title="目录"></a>目录</h1><p>[TOC]</p>
<h1 id="第01章-高性能架构模式"><a href="#第01章-高性能架构模式" class="headerlink" title="第01章 高性能架构模式"></a>第01章 高性能架构模式</h1><p>互联网业务兴起之后，海量用户加上海量数据的特点，单个数据库服务器已经难以满足业务需要，必须考虑数据库集群的方式来提升性能。高性能数据库集群的<code>第一种方式是“读写分离”</code>，<code>第二种方式是“数据库分片”</code>。</p>
<h2 id="1、读写分离架构"><a href="#1、读写分离架构" class="headerlink" title="1、读写分离架构"></a>1、读写分离架构</h2><p><strong>读写分离原理：</strong>读写分离的基本原理是将数据库读写操作分散到不同的节点上，下面是其基本架构图：</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/362d22168bf344687ec0c206aa115807.jpg" alt="img"></p>
<p><strong>读写分离的基本实现：</strong></p>
<ul>
<li><code>主库负责处理事务性的增删改操作，从库负责处理查询操作</code>，能够有效的避免由数据更新导致的行锁，使得整个系统的查询性能得到极大的改善。</li>
<li>读写分离是<code>根据 SQL 语义的分析</code>，<code>将读操作和写操作分别路由至主库与从库</code>。</li>
<li>通过<code>一主多从</code>的配置方式，可以将查询请求均匀的分散到多个数据副本，能够进一步的提升系统的处理能力。 </li>
<li>使用<code>多主多从</code>的方式，不但能够提升系统的吞吐量，还能够提升系统的可用性，可以达到在任何一个数据库宕机，甚至磁盘物理损坏的情况下仍然不影响系统的正常运行。</li>
</ul>
<p><strong>下图展示了根据业务需要，将用户表的写操作和读操路由到不同的数据库的方案：</strong></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220804223138651.png" alt="image-20220804223138651"></p>
<p><strong>CAP 理论：</strong></p>
<p>CAP 定理（CAP theorem）又被称作布鲁尔定理（Brewer’s theorem），是加州大学伯克利分校的计算机科学家埃里克·布鲁尔（Eric Brewer）在 2000 年的 ACM PODC 上提出的一个猜想。<code>对于设计分布式系统的架构师来说，CAP 是必须掌握的理论。</code></p>
<p>在一个<code>分布式系统中</code>，当涉及读写操作时，只能保证一致性（Consistence）、可用性（Availability）、分区容错性（Partition Tolerance）三者中的两个，另外一个必须被牺牲。</p>
<ul>
<li>C 一致性（Consistency）：对某个指定的客户端来说，读操作保证能够返回最新的写操作结果</li>
<li>A 可用性（Availability）：非故障的节点在合理的时间内返回合理的响应<code>（不是错误和超时的响应）</code></li>
<li>P 分区容忍性（Partition Tolerance）：当出现网络分区后<code>（可能是丢包，也可能是连接中断，还可能是拥塞）</code>，系统能够继续“履行职责”</li>
</ul>
<p><strong>CAP特点：</strong></p>
<ul>
<li>在实际设计过程中，每个系统不可能只处理一种数据，而是包含多种类型的数据，<code>有的数据必须选择 CP，有的数据必须选择 AP，分布式系统理论上不可能选择 CA 架构。</code></li>
</ul>
<ul>
<li><p>CP：如下图所示，<code>为了保证一致性</code>，当发生分区现象后，N1 节点上的数据已经更新到 y，但由于 N1 和 N2 之间的复制通道中断，数据 y 无法同步到 N2，N2 节点上的数据还是 x。<code>这时客户端 C 访问 N2 时，N2 需要返回 Error，提示客户端 C“系统现在发生了错误”，</code>这种处理方式<code>违背了可用性</code>（Availability）的要求，因此 CAP 三者只能满足 CP。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/6e7d7bd54d7a4eb67918080863d354d7.png" alt="img"></p>
</li>
</ul>
<ul>
<li>AP：如下图所示，<code>为了保证可用性</code>，当发生分区现象后，N1 节点上的数据已经更新到 y，但由于 N1 和 N2 之间的复制通道中断，数据 y 无法同步到 N2，N2 节点上的数据还是 x。<code>这时客户端 C 访问 N2 时，N2 将当前自己拥有的数据 x 返回给客户端 C 了</code>，而实际上当前最新的数据已经是 y 了，这就<code>不满足一致性</code>（Consistency）的要求了，因此 CAP 三者只能满足 AP。注意：这里 N2 节点返回 x，虽然不是一个“正确”的结果，但是一个“合理”的结果，因为 x 是旧的数据，并不是一个错乱的值，只是不是最新的数据而已。</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/2ccafe41de9bd7f8dec4658f004310d6.png" alt="img"></p>
<ul>
<li><p>CAP 理论中的 <code>C 在实践中是不可能完美实现的</code>，在数据复制的过程中，节点N1 和节点 N2 的数据并不一致（强一致性）。即使无法做到<code>强一致性</code>，但应用可以采用适合的方式达到<code>最终一致性</code>。具有如下特点：</p>
<ul>
<li>基本可用（Basically Available）：分布式系统在出现故障时，允许损失部分可用性，即保证核心可用。</li>
<li>软状态（Soft State）：允许系统存在中间状态，而该中间状态不会影响系统整体可用性。这里的中间状态就是 CAP 理论中的数据不一致。</li>
<li><code>最终一致性（Eventual Consistency）：系统中的所有数据副本经过一定时间后，最终能够达到一致的状态。</code></li>
</ul>
</li>
</ul>
<h2 id="2、数据库分片架构"><a href="#2、数据库分片架构" class="headerlink" title="2、数据库分片架构"></a>2、数据库分片架构</h2><p><strong>读写分离的问题：</strong></p>
<p>读写分离分散了数据库读写操作的压力，但没有分散存储压力，为了满足业务数据存储的需求，就需要<code>将存储分散到多台数据库服务器上</code>。</p>
<p><strong>数据分片：</strong></p>
<p>将存放在单一数据库中的数据分散地存放至多个数据库或表中，以达到提升性能瓶颈以及可用性的效果。 数据分片的有效手段是对关系型数据库进行<code>分库和分表</code>。数据分片的拆分方式又分为<code>垂直分片和水平分片</code>。</p>
<h3 id="2-1、垂直分片"><a href="#2-1、垂直分片" class="headerlink" title="2.1、垂直分片"></a>2.1、垂直分片</h3><p><strong>垂直分库：</strong></p>
<p><code>按照业务拆分的方式称为垂直分片，又称为纵向拆分</code>，它的核心理念是专库专用。 在拆分之前，一个数据库由多个数据表构成，每个表对应着不同的业务。而拆分之后，则是按照业务将表进行归类，分布到不同的数据库中，从而将压力分散至不同的数据库。 </p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/71f41d46cc5c0405f4d4dc944b4350c9.jpg" alt="img"></p>
<p>下图展示了根据业务需要，将用户表和订单表垂直分片到不同的数据库的方案：</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220804221855449.png" alt="image-20220804221855449"></p>
<p>垂直拆分可以缓解数据量和访问量带来的问题，但无法根治。<code>如果垂直拆分之后，表中的数据量依然超过单节点所能承载的阈值，则需要水平分片来进一步处理。</code></p>
<p><strong>垂直分表：</strong></p>
<p><code>垂直分表适合将表中某些不常用的列，或者是占了大量空间的列拆分出去。</code></p>
<p>假设我们是一个婚恋网站，用户在筛选其他用户的时候，主要是用 age 和 sex 两个字段进行查询，而 nickname 和 description 两个字段主要用于展示，一般不会在业务查询中用到。description 本身又比较长，因此我们可以将这两个字段独立到另外一张表中，这样在查询 age 和 sex 时，就能带来一定的性能提升。</p>
<p>垂直分表引入的复杂性主要体现在表操作的数量要增加。例如，原来只要一次查询就可以获取 name、age、sex、nickname、description，现在需要两次查询，一次查询获取 name、age、sex，另外一次查询获取 nickname、description。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/136bc2f01919edcb8271df6f7e71af40.jpg" alt="img"></p>
<p><code>水平分表适合表行数特别大的表，水平分表属于水平分片</code>。</p>
<h3 id="2-2、水平分片"><a href="#2-2、水平分片" class="headerlink" title="2.2、水平分片"></a>2.2、水平分片</h3><p><code>水平分片又称为横向拆分。</code> 相对于垂直分片，它不再将数据根据业务逻辑分类，而是通过某个字段（或某几个字段），根据某种规则将数据分散至多个库或表中，每个分片仅包含数据的一部分。 例如：根据主键分片，偶数主键的记录放入 0 库（或表），奇数主键的记录放入 1 库（或表），如下图所示。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220804222212087.png" alt="image-20220804222212087"></p>
<p><code>单表进行切分后，是否将多个表分散在不同的数据库服务器中，可以根据实际的切分效果来确定。</code></p>
<ul>
<li><p><strong>水平分表：</strong>单表切分为多表后，新的表即使在同一个数据库服务器中，也可能带来可观的性能提升，如果性能能够满足业务要求，可以不拆分到多台数据库服务器，毕竟业务分库也会引入很多复杂性；</p>
</li>
<li><p><strong>水平分库：</strong>如果单表拆分为多表后，单台服务器依然无法满足性能要求，那就需要将多个表分散在不同的数据库服务器中。</p>
</li>
</ul>
<blockquote>
<p><strong>阿里巴巴Java开发手册：</strong></p>
<p>【推荐】单表行数超过 500 万行或者单表容量超过 2GB，才推荐进行分库分表。</p>
<p>说明：如果预计三年后的数据量根本达不到这个级别，<code>请不要在创建表时就分库分表</code>。</p>
</blockquote>
<h2 id="3、读写分离和数据分片架构"><a href="#3、读写分离和数据分片架构" class="headerlink" title="3、读写分离和数据分片架构"></a>3、读写分离和数据分片架构</h2><p> 下图展现了将数据分片与读写分离一同使用时，应用程序与数据库集群之间的复杂拓扑关系。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220804223321167.png" alt="image-20220804223321167"></p>
<h2 id="4、实现方式"><a href="#4、实现方式" class="headerlink" title="4、实现方式"></a>4、实现方式</h2><p>读写分离和数据分片具体的实现方式一般有两种：  <code>程序代码封装</code>和<code>中间件封装</code>。</p>
<h3 id="4-1、程序代码封装"><a href="#4-1、程序代码封装" class="headerlink" title="4.1、程序代码封装"></a>4.1、程序代码封装</h3><p>程序代码封装指在代码中抽象一个<code>数据访问层（或中间层封装）</code>，实现读写操作分离和数据库服务器连接的管理。</p>
<p><strong>其基本架构是：</strong>以读写分离为例</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/f8d538f9201e3ebee37dfdcd1922e9df.jpg" alt="img"></p>
<h3 id="4-2、中间件封装"><a href="#4-2、中间件封装" class="headerlink" title="4.2、中间件封装"></a>4.2、中间件封装</h3><p>中间件封装指的是<code>独立一套系统出来</code>，实现读写操作分离和数据库服务器连接的管理。对于业务服务器来说，访问中间件和访问数据库没有区别，在业务服务器看来，中间件就是一个数据库服务器。</p>
<p><strong>基本架构是：</strong>以读写分离为例</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/2a2dba7f07581fd055d9cd5a3aa8388e.jpg" alt="img"></p>
<h3 id="4-3、常用解决方案"><a href="#4-3、常用解决方案" class="headerlink" title="4.3、常用解决方案"></a>4.3、常用解决方案</h3><p>Apache ShardingSphere（程序级别和中间件级别）</p>
<p>MyCat（数据库中间件） </p>
<h1 id="第02章-ShardingSphere"><a href="#第02章-ShardingSphere" class="headerlink" title="第02章 ShardingSphere"></a>第02章 ShardingSphere</h1><h2 id="1、简介"><a href="#1、简介" class="headerlink" title="1、简介"></a>1、简介</h2><p>官网：<a target="_blank" rel="noopener" href="https://shardingsphere.apache.org/index_zh.html">https://shardingsphere.apache.org/index_zh.html</a></p>
<p>文档：<a target="_blank" rel="noopener" href="https://shardingsphere.apache.org/document/5.1.1/cn/overview/">https://shardingsphere.apache.org/document/5.1.1/cn/overview/</a></p>
<p>Apache ShardingSphere 由 JDBC、Proxy 和 Sidecar（规划中）这 3 款既能够独立部署，又支持混合部署配合使用的产品组成。 </p>
<h2 id="2、ShardingSphere-JDBC"><a href="#2、ShardingSphere-JDBC" class="headerlink" title="2、ShardingSphere-JDBC"></a>2、ShardingSphere-JDBC</h2><p><strong>程序代码封装</strong></p>
<p>定位为轻量级 Java 框架，<code>在 Java 的 JDBC 层提供的额外服务</code>。 它使用客户端直连数据库，<code>以 jar 包形式提供服务</code>，无需额外部署和依赖，可理解为增强版的 JDBC 驱动，完全兼容 JDBC 和各种 ORM 框架。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220804195402870.png" alt="image-20220804195402870"></p>
<h2 id="3、ShardingSphere-Proxy"><a href="#3、ShardingSphere-Proxy" class="headerlink" title="3、ShardingSphere-Proxy"></a>3、ShardingSphere-Proxy</h2><p><strong>中间件封装</strong></p>
<p>定位为透明化的<code>数据库代理端</code>，提供封装了数据库二进制协议的服务端版本，用于完成对异构语言的支持。 目前提供 MySQL 和 PostgreSQL版本，它可以使用任何兼容 MySQL/PostgreSQL 协议的访问客户端（如：MySQL Command Client, MySQL Workbench, Navicat 等）操作数据，对 DBA 更加友好。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220804195432673.png" alt="image-20220804195432673"></p>
<h1 id="第03章-MySQL主从同步"><a href="#第03章-MySQL主从同步" class="headerlink" title="第03章 MySQL主从同步"></a>第03章 MySQL主从同步</h1><h2 id="1、MySQL主从同步原理"><a href="#1、MySQL主从同步原理" class="headerlink" title="1、MySQL主从同步原理"></a>1、MySQL主从同步原理</h2><p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220714133617856.png" alt="img"></p>
<p><strong>基本原理：</strong></p>
<p>slave会从master读取binlog来进行数据同步</p>
<p><strong>具体步骤：</strong></p>
<ul>
<li><code>step1：</code>master将数据改变记录到<code>二进制日志（binary log）</code>中。</li>
<li><code>step2：</code> 当slave上执行 <code>start slave</code> 命令之后，slave会创建一个 <code>IO 线程</code>用来连接master，请求master中的binlog。</li>
<li><code>step3：</code>当slave连接master时，master会创建一个 <code>log dump 线程</code>，用于发送 binlog 的内容。在读取 binlog 的内容的操作中，会对主节点上的 binlog 加锁，当读取完成并发送给从服务器后解锁。</li>
<li><code>step4：</code>IO 线程接收主节点 binlog dump 进程发来的更新之后，保存到 <code>中继日志（relay log）</code> 中。</li>
<li><code>step5：</code>slave的<code>SQL线程</code>，读取relay log日志，并解析成具体操作，从而实现主从操作一致，最终数据一致。</li>
</ul>
<h2 id="2、一主多从配置"><a href="#2、一主多从配置" class="headerlink" title="2、一主多从配置"></a>2、一主多从配置</h2><p>服务器规划：使用<code>docker</code>方式创建，<code>主从服务器IP一致，端口号不一致</code></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220807183231101.png" alt="image-20220807183231101"></p>
<ul>
<li>主服务器：容器名<code>xiaofei-mysql-master</code>，端口<code>3306</code></li>
<li>从服务器：容器名<code>xiaofei-mysql-slave1</code>，端口<code>3307</code></li>
<li>从服务器：容器名<code>xiaofei-mysql-slave2</code>，端口<code>3308</code></li>
</ul>
<p><strong>注意：</strong>如果此时防火墙是开启的，<code>则先关闭防火墙，并重启docker</code>，否则后续安装的MySQL无法启动</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">关闭docker</span></span><br><span class="line">systemctl stop docker</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">关闭防火墙</span></span><br><span class="line">systemctl stop firewalld</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">启动docker</span></span><br><span class="line">systemctl start docker</span><br></pre></td></tr></table></figure>
<h3 id="2-1、准备主服务器"><a href="#2-1、准备主服务器" class="headerlink" title="2.1、准备主服务器"></a>2.1、准备主服务器</h3><ul>
<li><strong>step1：在docker中创建并启动MySQL主服务器：</strong><code>端口3306</code></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">docker run -d \</span><br><span class="line">-p 3306:3306 \</span><br><span class="line">-v /xiaofei/mysql/master/conf:/etc/mysql/conf.d \</span><br><span class="line">-v /xiaofei/mysql/master/data:/var/lib/mysql \</span><br><span class="line">-e MYSQL_ROOT_PASSWORD=123456 \</span><br><span class="line">--name xiaofei-mysql-master \</span><br><span class="line">mysql:8.0.29</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step2：创建MySQL主服务器配置文件：</strong> </li>
</ul>
<p>默认情况下MySQL的binlog日志是自动开启的，可以通过如下配置定义一些可选配置</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vim /xiaofei/mysql/master/conf/my.cnf</span><br></pre></td></tr></table></figure>
<p>配置如下内容</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">[mysqld]</span></span><br><span class="line"><span class="comment"># 服务器唯一id，默认值1</span></span><br><span class="line"><span class="attr">server-id</span>=<span class="string">1</span></span><br><span class="line"><span class="comment"># 设置日志格式，默认值ROW</span></span><br><span class="line"><span class="attr">binlog_format</span>=<span class="string">STATEMENT</span></span><br><span class="line"><span class="comment"># 二进制日志名，默认binlog</span></span><br><span class="line"><span class="comment"># log-bin=binlog</span></span><br><span class="line"><span class="comment"># 设置需要复制的数据库，默认复制全部数据库</span></span><br><span class="line"><span class="comment">#binlog-do-db=mytestdb</span></span><br><span class="line"><span class="comment"># 设置不需要复制的数据库</span></span><br><span class="line"><span class="comment">#binlog-ignore-db=mysql</span></span><br><span class="line"><span class="comment">#binlog-ignore-db=infomation_schema</span></span><br></pre></td></tr></table></figure>
<p>重启MySQL容器</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker restart xiaofei-mysql-master</span><br></pre></td></tr></table></figure>
<p><code>binlog格式说明：</code></p>
<ul>
<li>binlog_format=STATEMENT：日志记录的是主机数据库的<code>写指令</code>，性能高，但是now()之类的函数以及获取系统参数的操作会出现主从数据不同步的问题。</li>
<li>binlog_format=ROW（默认）：日志记录的是主机数据库的<code>写后的数据</code>，批量操作时性能较差，解决now()或者  user()或者  @@hostname 等操作在主从机器上不一致的问题。</li>
<li>binlog_format=MIXED：是以上两种level的混合使用，有函数用ROW，没函数用STATEMENT，但是无法识别系统变量</li>
</ul>
<p><code>binlog-ignore-db和binlog-do-db的优先级问题：</code></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/0.08703112216569037.png" alt="img"></p>
<ul>
<li><strong>step3：使用命令行登录MySQL主服务器：</strong></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器：<span class="built_in">env</span> LANG=C.UTF-8 避免容器中显示中文乱码</span></span><br><span class="line">docker exec -it xiaofei-mysql-master env LANG=C.UTF-8 /bin/bash</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器内的mysql命令行</span></span><br><span class="line">mysql -uroot -p</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">修改默认密码校验方式</span></span><br><span class="line">ALTER USER &#x27;root&#x27;@&#x27;%&#x27; IDENTIFIED WITH mysql_native_password BY &#x27;123456&#x27;;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step4：主机中创建slave用户：</strong></li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 创建slave用户</span></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">USER</span> <span class="string">&#x27;xiaofei_slave&#x27;</span>@<span class="string">&#x27;%&#x27;</span>;</span><br><span class="line"><span class="comment">-- 设置密码</span></span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">USER</span> <span class="string">&#x27;xiaofei_slave&#x27;</span>@<span class="string">&#x27;%&#x27;</span> IDENTIFIED <span class="keyword">WITH</span> mysql_native_password <span class="keyword">BY</span> <span class="string">&#x27;123456&#x27;</span>;</span><br><span class="line"><span class="comment">-- 授予复制权限</span></span><br><span class="line"><span class="keyword">GRANT</span> REPLICATION SLAVE <span class="keyword">ON</span> <span class="operator">*</span>.<span class="operator">*</span> <span class="keyword">TO</span> <span class="string">&#x27;xiaofei_slave&#x27;</span>@<span class="string">&#x27;%&#x27;</span>;</span><br><span class="line"><span class="comment">-- 刷新权限</span></span><br><span class="line">FLUSH PRIVILEGES;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step5：主机中查询master状态：</strong></li>
</ul>
<p>执行完此步骤后<code>不要再操作主服务器MYSQL</code>，防止主服务器状态值变化</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SHOW</span> MASTER STATUS;</span><br></pre></td></tr></table></figure>
<p>记下<code>File</code>和<code>Position</code>的值。执行完此步骤后不要再操作主服务器MYSQL，防止主服务器状态值变化。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220804191852164.png" alt="image-20220804191852164"></p>
<h3 id="2-2、准备从服务器"><a href="#2-2、准备从服务器" class="headerlink" title="2.2、准备从服务器"></a>2.2、准备从服务器</h3><p>可以配置多台从机slave1、slave2…，这里以配置slave1为例</p>
<ul>
<li><strong>step1：在docker中创建并启动MySQL从服务器：</strong><code>端口3307</code></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">docker run -d \</span><br><span class="line">-p 3307:3306 \</span><br><span class="line">-v /xiaofei/mysql/slave1/conf:/etc/mysql/conf.d \</span><br><span class="line">-v /xiaofei/mysql/slave1/data:/var/lib/mysql \</span><br><span class="line">-e MYSQL_ROOT_PASSWORD=123456 \</span><br><span class="line">--name xiaofei-mysql-slave1 \</span><br><span class="line">mysql:8.0.29</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step2：创建MySQL从服务器配置文件：</strong> </li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vim /xiaofei/mysql/slave1/conf/my.cnf</span><br></pre></td></tr></table></figure>
<p>配置如下内容：</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">[mysqld]</span></span><br><span class="line"><span class="comment"># 服务器唯一id，每台服务器的id必须不同，如果配置其他从机，注意修改id</span></span><br><span class="line"><span class="attr">server-id</span>=<span class="string">2</span></span><br><span class="line"><span class="comment"># 中继日志名，默认xxxxxxxxxxxx-relay-bin</span></span><br><span class="line"><span class="comment">#relay-log=relay-bin</span></span><br></pre></td></tr></table></figure>
<p>重启MySQL容器</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker restart xiaofei-mysql-slave1</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step3：使用命令行登录MySQL从服务器：</strong></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器：</span></span><br><span class="line">docker exec -it xiaofei-mysql-slave1 env LANG=C.UTF-8 /bin/bash</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器内的mysql命令行</span></span><br><span class="line">mysql -uroot -p</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">修改默认密码校验方式</span></span><br><span class="line">ALTER USER &#x27;root&#x27;@&#x27;%&#x27; IDENTIFIED WITH mysql_native_password BY &#x27;123456&#x27;;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step4：在从机上配置主从关系：</strong></li>
</ul>
<p>在<strong>从机</strong>上执行以下SQL操作</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">CHANGE MASTER <span class="keyword">TO</span> MASTER_HOST<span class="operator">=</span><span class="string">&#x27;192.168.100.201&#x27;</span>, </span><br><span class="line">MASTER_USER<span class="operator">=</span><span class="string">&#x27;xiaofei_slave&#x27;</span>,MASTER_PASSWORD<span class="operator">=</span><span class="string">&#x27;123456&#x27;</span>, MASTER_PORT<span class="operator">=</span><span class="number">3306</span>,</span><br><span class="line">MASTER_LOG_FILE<span class="operator">=</span><span class="string">&#x27;binlog.000003&#x27;</span>,MASTER_LOG_POS<span class="operator">=</span><span class="number">1357</span>; </span><br></pre></td></tr></table></figure>
<h3 id="2-3、启动主从同步"><a href="#2-3、启动主从同步" class="headerlink" title="2.3、启动主从同步"></a>2.3、启动主从同步</h3><p>启动从机的复制功能，执行SQL：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">START</span> SLAVE;</span><br><span class="line"><span class="comment">-- 查看状态（不需要分号）</span></span><br><span class="line"><span class="keyword">SHOW</span> SLAVE STATUS\G</span><br></pre></td></tr></table></figure>
<p><strong>两个关键进程：</strong>下面两个参数都是Yes，则说明主从配置成功！</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220715000533951.png" alt="img"></p>
<h3 id="2-4、实现主从同步"><a href="#2-4、实现主从同步" class="headerlink" title="2.4、实现主从同步"></a>2.4、实现主从同步</h3><p>在主机中执行以下SQL，在从机中查看数据库、表和数据是否已经被同步</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> DATABASE db_user;</span><br><span class="line">USE db_user;</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> t_user (</span><br><span class="line"> id <span class="type">BIGINT</span> AUTO_INCREMENT,</span><br><span class="line"> uname <span class="type">VARCHAR</span>(<span class="number">30</span>),</span><br><span class="line"> <span class="keyword">PRIMARY</span> KEY (id)</span><br><span class="line">);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> t_user(uname) <span class="keyword">VALUES</span>(<span class="string">&#x27;zhang3&#x27;</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> t_user(uname) <span class="keyword">VALUES</span>(@<span class="variable">@hostname</span>);</span><br></pre></td></tr></table></figure>
<h3 id="2-5、停止和重置"><a href="#2-5、停止和重置" class="headerlink" title="2.5、停止和重置"></a>2.5、停止和重置</h3><p>需要的时候，可以使用如下SQL语句</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 在从机上执行。功能说明：停止I/O 线程和SQL线程的操作。</span></span><br><span class="line">stop slave; </span><br><span class="line"></span><br><span class="line"><span class="comment">-- 在从机上执行。功能说明：用于删除SLAVE数据库的relaylog日志文件，并重新启用新的relaylog文件。</span></span><br><span class="line">reset slave;</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 在主机上执行。功能说明：删除所有的binglog日志文件，并将日志索引文件清空，重新开始所有新的日志文件。</span></span><br><span class="line"><span class="comment">-- 用于第一次进行搭建主从库时，进行主库binlog初始化工作；</span></span><br><span class="line">reset master;</span><br></pre></td></tr></table></figure>
<h3 id="2-6、常见问题"><a href="#2-6、常见问题" class="headerlink" title="2.6、常见问题"></a><strong>2.6、常见问题</strong></h3><h4 id="问题1"><a href="#问题1" class="headerlink" title="问题1"></a>问题1</h4><p>启动主从同步后，常见错误是<code>Slave_IO_Running： No 或者 Connecting</code> 的情况，此时查看下方的 <code>Last_IO_ERROR</code>错误日志，根据日志中显示的错误信息在网上搜索解决方案即可</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220714235426120.png" alt="img"></p>
<p><strong>典型的错误例如：</strong><code>Last_IO_Error: Got fatal error 1236 from master when reading data from binary log: &#39;Client requested master to start replication from position &gt; file size&#39;</code></p>
<p><strong>解决方案：</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 在从机停止slave</span></span><br><span class="line">SLAVE STOP;</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 在主机查看mater状态</span></span><br><span class="line"><span class="keyword">SHOW</span> MASTER STATUS;</span><br><span class="line"><span class="comment">-- 在主机刷新日志</span></span><br><span class="line">FLUSH LOGS;</span><br><span class="line"><span class="comment">-- 再次在主机查看mater状态（会发现File和Position发生了变化）</span></span><br><span class="line"><span class="keyword">SHOW</span> MASTER STATUS;</span><br><span class="line"><span class="comment">-- 修改从机连接主机的SQL，并重新连接即可</span></span><br></pre></td></tr></table></figure>
<h4 id="问题2"><a href="#问题2" class="headerlink" title="问题2"></a>问题2</h4><p>启动docker容器后提示 <code>WARNING: IPv4 forwarding is disabled. Networking will not work.</code></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220715004850504.png" alt="img"></p>
<p>此错误，虽然不影响主从同步的搭建，但是如果想从远程客户端通过以下方式连接docker中的MySQL则没法连接</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">C:\Users\administrator&gt;mysql -h 192.168.100.201 -P 3306 -u root -p</span><br></pre></td></tr></table></figure>
<p><strong>解决方案：</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">修改配置文件：</span></span><br><span class="line">vim /usr/lib/sysctl.d/00-system.conf</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">追加</span></span><br><span class="line">net.ipv4.ip_forward=1</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">接着重启网络</span></span><br><span class="line">systemctl restart network</span><br></pre></td></tr></table></figure>
<h1 id="第04章-ShardingSphere-JDBC读写分离"><a href="#第04章-ShardingSphere-JDBC读写分离" class="headerlink" title="第04章 ShardingSphere-JDBC读写分离"></a>第04章 ShardingSphere-JDBC读写分离</h1><h2 id="1、创建SpringBoot程序"><a href="#1、创建SpringBoot程序" class="headerlink" title="1、创建SpringBoot程序"></a>1、创建SpringBoot程序</h2><h3 id="1-1、创建项目"><a href="#1-1、创建项目" class="headerlink" title="1.1、创建项目"></a>1.1、创建项目</h3><p>项目类型：Spring Initializr</p>
<p>SpringBoot脚手架：<a target="_blank" rel="noopener" href="http://start.aliyun.com">http://start.aliyun.com</a></p>
<p>项目名：sharding-jdbc-demo</p>
<p>SpringBoot版本：2.3.7.RELEASE</p>
<h3 id="1-2、添加依赖"><a href="#1-2、添加依赖" class="headerlink" title="1.2、添加依赖"></a>1.2、添加依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.shardingsphere<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>shardingsphere-jdbc-core-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.1.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">scope</span>&gt;</span>runtime<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.3.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    </span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">exclusions</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">exclusion</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.junit.vintage<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>junit-vintage-engine<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">exclusion</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">exclusions</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="1-3、创建实体类"><a href="#1-3、创建实体类" class="headerlink" title="1.3、创建实体类"></a>1.3、创建实体类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo.entity;</span><br><span class="line"></span><br><span class="line"><span class="meta">@TableName(&quot;t_user&quot;)</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line">    <span class="meta">@TableId(type = IdType.AUTO)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="keyword">private</span> String uname;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-4、创建Mapper"><a href="#1-4、创建Mapper" class="headerlink" title="1.4、创建Mapper"></a>1.4、创建Mapper</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo.mapper;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Mapper</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserMapper</span> <span class="keyword">extends</span> <span class="title class_">BaseMapper</span>&lt;User&gt; &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-5、配置读写分离"><a href="#1-5、配置读写分离" class="headerlink" title="1.5、配置读写分离"></a>1.5、配置读写分离</h3><p>application.properties：</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 应用名称</span></span><br><span class="line"><span class="attr">spring.application.name</span>=<span class="string">sharging-jdbc-demo</span></span><br><span class="line"><span class="comment"># 开发环境设置</span></span><br><span class="line"><span class="attr">spring.profiles.active</span>=<span class="string">dev</span></span><br><span class="line"><span class="comment"># 内存模式</span></span><br><span class="line"><span class="attr">spring.shardingsphere.mode.type</span>=<span class="string">Memory</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 配置真实数据源</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.names</span>=<span class="string">master,slave1,slave2</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 配置第 1 个数据源</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.master.type</span>=<span class="string">com.zaxxer.hikari.HikariDataSource</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.master.driver-class-name</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.master.jdbc-url</span>=<span class="string">jdbc:mysql://192.168.100.201:3306/db_user</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.master.username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.master.password</span>=<span class="string">123456</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 配置第 2 个数据源</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.slave1.type</span>=<span class="string">com.zaxxer.hikari.HikariDataSource</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.slave1.driver-class-name</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.slave1.jdbc-url</span>=<span class="string">jdbc:mysql://192.168.100.201:3307/db_user</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.slave1.username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.slave1.password</span>=<span class="string">123456</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 配置第 3 个数据源</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.slave2.type</span>=<span class="string">com.zaxxer.hikari.HikariDataSource</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.slave2.driver-class-name</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.slave2.jdbc-url</span>=<span class="string">jdbc:mysql://192.168.100.201:3308/db_user</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.slave2.username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.slave2.password</span>=<span class="string">123456</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 读写分离类型，如: Static，Dynamic</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.readwrite-splitting.data-sources.myds.type</span>=<span class="string">Static</span></span><br><span class="line"><span class="comment"># 写数据源名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.readwrite-splitting.data-sources.myds.props.write-data-source-name</span>=<span class="string">master</span></span><br><span class="line"><span class="comment"># 读数据源名称，多个从数据源用逗号分隔</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.readwrite-splitting.data-sources.myds.props.read-data-source-names</span>=<span class="string">slave1,slave2</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 负载均衡算法名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.readwrite-splitting.data-sources.myds.load-balancer-name</span>=<span class="string">alg_round</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 负载均衡算法配置</span></span><br><span class="line"><span class="comment"># 负载均衡算法类型</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.readwrite-splitting.load-balancers.alg_round.type</span>=<span class="string">ROUND_ROBIN</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.readwrite-splitting.load-balancers.alg_random.type</span>=<span class="string">RANDOM</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.readwrite-splitting.load-balancers.alg_weight.type</span>=<span class="string">WEIGHT</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.readwrite-splitting.load-balancers.alg_weight.props.slave1</span>=<span class="string">1</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.readwrite-splitting.load-balancers.alg_weight.props.slave2</span>=<span class="string">2</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 打印SQl</span></span><br><span class="line"><span class="attr">spring.shardingsphere.props.sql-show</span>=<span class="string">true</span></span><br></pre></td></tr></table></figure>
<h2 id="2、测试"><a href="#2、测试" class="headerlink" title="2、测试"></a>2、测试</h2><h3 id="2-1、读写分离测试"><a href="#2-1、读写分离测试" class="headerlink" title="2.1、读写分离测试"></a>2.1、读写分离测试</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ReadwriteTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 写入数据的测试</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testInsert</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        user.setUname(<span class="string">&quot;张三丰&quot;</span>);</span><br><span class="line">        userMapper.insert(user);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-2、事务测试"><a href="#2-2、事务测试" class="headerlink" title="2.2、事务测试"></a>2.2、事务测试</h3><p>为了保证主从库间的事务一致性，避免跨服务的分布式事务，ShardingSphere-JDBC的<code>主从模型中，事务中的数据读写均用主库</code>。</p>
<ul>
<li>不添加@Transactional：insert对主库操作，select对从库操作</li>
<li>添加@Transactional：则insert和select均对主库操作</li>
<li><strong>注意：</strong>在JUnit环境下的@Transactional注解，默认情况下就会对事务进行回滚（即使在没加注解@Rollback，也会对事务回滚）</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 事务测试</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Transactional</span><span class="comment">//开启事务</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testTrans</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">    user.setUname(<span class="string">&quot;铁锤&quot;</span>);</span><br><span class="line">    userMapper.insert(user);</span><br><span class="line"></span><br><span class="line">    List&lt;User&gt; users = userMapper.selectList(<span class="literal">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-3、负载均衡测试"><a href="#2-3、负载均衡测试" class="headerlink" title="2.3、负载均衡测试"></a>2.3、负载均衡测试</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 读数据测试</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testSelectAll</span><span class="params">()</span>&#123;</span><br><span class="line">    List&lt;User&gt; users = userMapper.selectList(<span class="literal">null</span>);</span><br><span class="line">    List&lt;User&gt; users = userMapper.selectList(<span class="literal">null</span>);<span class="comment">//执行第二次测试负载均衡</span></span><br><span class="line">    users.forEach(System.out::println);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>也可以在web请求中测试负载均衡</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo.controller;</span><br><span class="line"></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/userController&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserController</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 测试负载均衡策略</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;selectAll&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">selectAll</span><span class="params">()</span>&#123;</span><br><span class="line">        List&lt;User&gt; users = userMapper.selectList(<span class="literal">null</span>);</span><br><span class="line">        users.forEach(System.out::println);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="第05章-ShardingSphere-JDBC垂直分片"><a href="#第05章-ShardingSphere-JDBC垂直分片" class="headerlink" title="第05章 ShardingSphere-JDBC垂直分片"></a>第05章 ShardingSphere-JDBC垂直分片</h1><h2 id="1、准备服务器"><a href="#1、准备服务器" class="headerlink" title="1、准备服务器"></a>1、准备服务器</h2><p>服务器规划：使用<code>docker</code>方式创建如下容器</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220807232456342.png" alt="image-20220807232456342"></p>
<ul>
<li><p>服务器：容器名<code>server-user</code>，端口<code>3301</code></p>
</li>
<li><p>服务器：容器名<code>server-order</code>，端口<code>3302</code></p>
</li>
</ul>
<h3 id="1-1、创建server-user容器"><a href="#1-1、创建server-user容器" class="headerlink" title="1.1、创建server-user容器"></a>1.1、创建server-user容器</h3><ul>
<li><strong>step1：创建容器：</strong></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">docker run -d \</span><br><span class="line">-p 3301:3306 \</span><br><span class="line">-v /xiaofei/server/user/conf:/etc/mysql/conf.d \</span><br><span class="line">-v /xiaofei/server/user/data:/var/lib/mysql \</span><br><span class="line">-e MYSQL_ROOT_PASSWORD=123456 \</span><br><span class="line">--name server-user \</span><br><span class="line">mysql:8.0.29</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step2：登录MySQL服务器：</strong></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器：</span></span><br><span class="line">docker exec -it server-user env LANG=C.UTF-8 /bin/bash</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器内的mysql命令行</span></span><br><span class="line">mysql -uroot -p</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">修改默认密码插件</span></span><br><span class="line">ALTER USER &#x27;root&#x27;@&#x27;%&#x27; IDENTIFIED WITH mysql_native_password BY &#x27;123456&#x27;;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step3：创建数据库：</strong></li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> DATABASE db_user;</span><br><span class="line">USE db_user;</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> t_user (</span><br><span class="line"> id <span class="type">BIGINT</span> AUTO_INCREMENT,</span><br><span class="line"> uname <span class="type">VARCHAR</span>(<span class="number">30</span>),</span><br><span class="line"> <span class="keyword">PRIMARY</span> KEY (id)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h3 id="1-2、创建server-order容器"><a href="#1-2、创建server-order容器" class="headerlink" title="1.2、创建server-order容器"></a>1.2、创建server-order容器</h3><ul>
<li><strong>step1：创建容器：</strong></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">docker run -d \</span><br><span class="line">-p 3302:3306 \</span><br><span class="line">-v /xiaofei/server/order/conf:/etc/mysql/conf.d \</span><br><span class="line">-v /xiaofei/server/order/data:/var/lib/mysql \</span><br><span class="line">-e MYSQL_ROOT_PASSWORD=123456 \</span><br><span class="line">--name server-order \</span><br><span class="line">mysql:8.0.29</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step2：登录MySQL服务器：</strong></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器：</span></span><br><span class="line">docker exec -it server-order env LANG=C.UTF-8 /bin/bash</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器内的mysql命令行</span></span><br><span class="line">mysql -uroot -p</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">修改默认密码插件</span></span><br><span class="line">ALTER USER &#x27;root&#x27;@&#x27;%&#x27; IDENTIFIED WITH mysql_native_password BY &#x27;123456&#x27;;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step3：创建数据库：</strong></li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> DATABASE db_order;</span><br><span class="line">USE db_order;</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> t_order (</span><br><span class="line">  id <span class="type">BIGINT</span> AUTO_INCREMENT,</span><br><span class="line">  order_no <span class="type">VARCHAR</span>(<span class="number">30</span>),</span><br><span class="line">  user_id <span class="type">BIGINT</span>,</span><br><span class="line">  amount <span class="type">DECIMAL</span>(<span class="number">10</span>,<span class="number">2</span>),</span><br><span class="line">  <span class="keyword">PRIMARY</span> KEY(id) </span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h2 id="2、程序实现"><a href="#2、程序实现" class="headerlink" title="2、程序实现"></a>2、程序实现</h2><h3 id="2-1、创建实体类"><a href="#2-1、创建实体类" class="headerlink" title="2.1、创建实体类"></a>2.1、创建实体类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo.entity;</span><br><span class="line"></span><br><span class="line"><span class="meta">@TableName(&quot;t_order&quot;)</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Order</span> &#123;</span><br><span class="line">    <span class="meta">@TableId(type = IdType.AUTO)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="keyword">private</span> String orderNo;</span><br><span class="line">    <span class="keyword">private</span> Long userId;</span><br><span class="line">    <span class="keyword">private</span> BigDecimal amount;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-2、创建Mapper"><a href="#2-2、创建Mapper" class="headerlink" title="2.2、创建Mapper"></a>2.2、创建Mapper</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo.mapper;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Mapper</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">OrderMapper</span> <span class="keyword">extends</span> <span class="title class_">BaseMapper</span>&lt;Order&gt; &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-3、配置垂直分片"><a href="#2-3、配置垂直分片" class="headerlink" title="2.3、配置垂直分片"></a>2.3、配置垂直分片</h3><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 应用名称</span></span><br><span class="line"><span class="attr">spring.application.name</span>=<span class="string">sharding-jdbc-demo</span></span><br><span class="line"><span class="comment"># 环境设置</span></span><br><span class="line"><span class="attr">spring.profiles.active</span>=<span class="string">dev</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 配置真实数据源</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.names</span>=<span class="string">server-user,server-order</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 配置第 1 个数据源</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-user.type</span>=<span class="string">com.zaxxer.hikari.HikariDataSource</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-user.driver-class-name</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-user.jdbc-url</span>=<span class="string">jdbc:mysql://192.168.100.201:3301/db_user</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-user.username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-user.password</span>=<span class="string">123456</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 配置第 2 个数据源</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.type</span>=<span class="string">com.zaxxer.hikari.HikariDataSource</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.driver-class-name</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.jdbc-url</span>=<span class="string">jdbc:mysql://192.168.100.201:3302/db_order</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.password</span>=<span class="string">123456</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 标准分片表配置（数据节点）</span></span><br><span class="line"><span class="comment"># spring.shardingsphere.rules.sharding.tables.&lt;table-name&gt;.actual-data-nodes=值</span></span><br><span class="line"><span class="comment"># 值由数据源名 + 表名组成，以小数点分隔。</span></span><br><span class="line"><span class="comment"># &lt;table-name&gt;：逻辑表名</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_user.actual-data-nodes</span>=<span class="string">server-user.t_user</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order.actual-data-nodes</span>=<span class="string">server-order.t_order</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 打印SQL</span></span><br><span class="line"><span class="attr">spring.shardingsphere.props.sql-show</span>=<span class="string">true</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="3、测试垂直分片"><a href="#3、测试垂直分片" class="headerlink" title="3、测试垂直分片"></a>3、测试垂直分片</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ShardingTest</span> &#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> OrderMapper orderMapper;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 垂直分片：插入数据测试</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testInsertOrderAndUser</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        user.setUname(<span class="string">&quot;强哥&quot;</span>);</span><br><span class="line">        userMapper.insert(user);</span><br><span class="line"></span><br><span class="line">        <span class="type">Order</span> <span class="variable">order</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Order</span>();</span><br><span class="line">        order.setOrderNo(<span class="string">&quot;xiaofei001&quot;</span>);</span><br><span class="line">        order.setUserId(user.getId());</span><br><span class="line">        order.setAmount(<span class="keyword">new</span> <span class="title class_">BigDecimal</span>(<span class="number">100</span>));</span><br><span class="line">        orderMapper.insert(order);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 垂直分片：查询数据测试</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testSelectFromOrderAndUser</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> userMapper.selectById(<span class="number">1L</span>);</span><br><span class="line">        <span class="type">Order</span> <span class="variable">order</span> <span class="operator">=</span> orderMapper.selectById(<span class="number">1L</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="常见错误"><a href="#常见错误" class="headerlink" title="常见错误"></a>常见错误</h3><p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220810163534068.png" alt="image-20220810163534068"></p>
<p>ShardingSphere-JDBC远程连接的方式默认的密码加密规则是：mysql_native_password</p>
<p>因此需要在服务器端修改服务器的密码加密规则，如下：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">USER</span> <span class="string">&#x27;root&#x27;</span>@<span class="string">&#x27;%&#x27;</span> IDENTIFIED <span class="keyword">WITH</span> mysql_native_password <span class="keyword">BY</span> <span class="string">&#x27;123456&#x27;</span>;</span><br></pre></td></tr></table></figure>
<h1 id="第06章-ShardingSphere-JDBC水平分片"><a href="#第06章-ShardingSphere-JDBC水平分片" class="headerlink" title="第06章 ShardingSphere-JDBC水平分片"></a>第06章 ShardingSphere-JDBC水平分片</h1><h2 id="1、准备服务器-1"><a href="#1、准备服务器-1" class="headerlink" title="1、准备服务器"></a>1、准备服务器</h2><p>服务器规划：使用<code>docker</code>方式创建如下容器</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220808033239206.png" alt="image-20220808033239206"></p>
<ul>
<li><p>服务器：容器名<code>server-order0</code>，端口<code>3310</code></p>
</li>
<li><p>服务器：容器名<code>server-order1</code>，端口<code>3311</code></p>
</li>
</ul>
<h3 id="1-1、创建server-order0容器"><a href="#1-1、创建server-order0容器" class="headerlink" title="1.1、创建server-order0容器"></a>1.1、创建server-order0容器</h3><ul>
<li><strong>step1：创建容器：</strong></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">docker run -d \</span><br><span class="line">-p 3310:3306 \</span><br><span class="line">-v /xiaofei/server/order0/conf:/etc/mysql/conf.d \</span><br><span class="line">-v /xiaofei/server/order0/data:/var/lib/mysql \</span><br><span class="line">-e MYSQL_ROOT_PASSWORD=123456 \</span><br><span class="line">--name server-order0 \</span><br><span class="line">mysql:8.0.29</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step2：登录MySQL服务器：</strong></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器：</span></span><br><span class="line">docker exec -it server-order0 env LANG=C.UTF-8 /bin/bash</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器内的mysql命令行</span></span><br><span class="line">mysql -uroot -p</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">修改默认密码插件</span></span><br><span class="line">ALTER USER &#x27;root&#x27;@&#x27;%&#x27; IDENTIFIED WITH mysql_native_password BY &#x27;123456&#x27;;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step3：创建数据库：</strong></li>
</ul>
<p><code>注意：</code>水平分片的id需要在业务层实现，<code>不能依赖数据库的主键自增</code></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> DATABASE db_order;</span><br><span class="line">USE db_order;</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> t_order0 (</span><br><span class="line">  id <span class="type">BIGINT</span>,</span><br><span class="line">  order_no <span class="type">VARCHAR</span>(<span class="number">30</span>),</span><br><span class="line">  user_id <span class="type">BIGINT</span>,</span><br><span class="line">  amount <span class="type">DECIMAL</span>(<span class="number">10</span>,<span class="number">2</span>),</span><br><span class="line">  <span class="keyword">PRIMARY</span> KEY(id) </span><br><span class="line">);</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> t_order1 (</span><br><span class="line">  id <span class="type">BIGINT</span>,</span><br><span class="line">  order_no <span class="type">VARCHAR</span>(<span class="number">30</span>),</span><br><span class="line">  user_id <span class="type">BIGINT</span>,</span><br><span class="line">  amount <span class="type">DECIMAL</span>(<span class="number">10</span>,<span class="number">2</span>),</span><br><span class="line">  <span class="keyword">PRIMARY</span> KEY(id) </span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h3 id="1-2、创建server-order1容器"><a href="#1-2、创建server-order1容器" class="headerlink" title="1.2、创建server-order1容器"></a>1.2、创建server-order1容器</h3><ul>
<li><strong>step1：创建容器：</strong></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">docker run -d \</span><br><span class="line">-p 3311:3306 \</span><br><span class="line">-v /xiaofei/server/order1/conf:/etc/mysql/conf.d \</span><br><span class="line">-v /xiaofei/server/order1/data:/var/lib/mysql \</span><br><span class="line">-e MYSQL_ROOT_PASSWORD=123456 \</span><br><span class="line">--name server-order1 \</span><br><span class="line">mysql:8.0.29</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step2：登录MySQL服务器：</strong></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器：</span></span><br><span class="line">docker exec -it server-order1 env LANG=C.UTF-8 /bin/bash</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">进入容器内的mysql命令行</span></span><br><span class="line">mysql -uroot -p</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">修改默认密码插件</span></span><br><span class="line">ALTER USER &#x27;root&#x27;@&#x27;%&#x27; IDENTIFIED WITH mysql_native_password BY &#x27;123456&#x27;;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>step3：创建数据库：</strong>和server-order0相同</li>
</ul>
<p><code>注意：</code>水平分片的id需要在业务层实现，不能依赖数据库的主键自增</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> DATABASE db_order;</span><br><span class="line">USE db_order;</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> t_order0 (</span><br><span class="line">  id <span class="type">BIGINT</span>,</span><br><span class="line">  order_no <span class="type">VARCHAR</span>(<span class="number">30</span>),</span><br><span class="line">  user_id <span class="type">BIGINT</span>,</span><br><span class="line">  amount <span class="type">DECIMAL</span>(<span class="number">10</span>,<span class="number">2</span>),</span><br><span class="line">  <span class="keyword">PRIMARY</span> KEY(id) </span><br><span class="line">);</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> t_order1 (</span><br><span class="line">  id <span class="type">BIGINT</span>,</span><br><span class="line">  order_no <span class="type">VARCHAR</span>(<span class="number">30</span>),</span><br><span class="line">  user_id <span class="type">BIGINT</span>,</span><br><span class="line">  amount <span class="type">DECIMAL</span>(<span class="number">10</span>,<span class="number">2</span>),</span><br><span class="line">  <span class="keyword">PRIMARY</span> KEY(id) </span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h2 id="2、基本水平分片"><a href="#2、基本水平分片" class="headerlink" title="2、基本水平分片"></a>2、基本水平分片</h2><h3 id="2-1、基本配置"><a href="#2-1、基本配置" class="headerlink" title="2.1、基本配置"></a>2.1、基本配置</h3><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#========================基本配置</span></span><br><span class="line"><span class="comment"># 应用名称</span></span><br><span class="line"><span class="attr">spring.application.name</span>=<span class="string">sharging-jdbc-demo</span></span><br><span class="line"><span class="comment"># 开发环境设置</span></span><br><span class="line"><span class="attr">spring.profiles.active</span>=<span class="string">dev</span></span><br><span class="line"><span class="comment"># 内存模式</span></span><br><span class="line"><span class="attr">spring.shardingsphere.mode.type</span>=<span class="string">Memory</span></span><br><span class="line"><span class="comment"># 打印SQl</span></span><br><span class="line"><span class="attr">spring.shardingsphere.props.sql-show</span>=<span class="string">true</span></span><br></pre></td></tr></table></figure>
<h3 id="2-2、数据源配置"><a href="#2-2、数据源配置" class="headerlink" title="2.2、数据源配置"></a>2.2、数据源配置</h3><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#========================数据源配置</span></span><br><span class="line"><span class="comment"># 配置真实数据源</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.names</span>=<span class="string">server-user,server-order0,server-order1</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 配置第 1 个数据源</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-user.type</span>=<span class="string">com.zaxxer.hikari.HikariDataSource</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-user.driver-class-name</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-user.jdbc-url</span>=<span class="string">jdbc:mysql://192.168.100.201:3301/db_user</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-user.username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-user.password</span>=<span class="string">123456</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 配置第 2 个数据源</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.type</span>=<span class="string">com.zaxxer.hikari.HikariDataSource</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.driver-class-name</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.jdbc-url</span>=<span class="string">jdbc:mysql://192.168.100.201:3310/db_order</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.password</span>=<span class="string">123456</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 配置第 3 个数据源</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.type</span>=<span class="string">com.zaxxer.hikari.HikariDataSource</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.driver-class-name</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.jdbc-url</span>=<span class="string">jdbc:mysql://192.168.100.201:3311/db_order</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">spring.shardingsphere.datasource.server-order.password</span>=<span class="string">123456</span></span><br></pre></td></tr></table></figure>
<h3 id="2-3、标椎分片表配置"><a href="#2-3、标椎分片表配置" class="headerlink" title="2.3、标椎分片表配置"></a>2.3、标椎分片表配置</h3><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#========================标准分片表配置（数据节点配置）</span></span><br><span class="line"><span class="comment"># spring.shardingsphere.rules.sharding.tables.&lt;table-name&gt;.actual-data-nodes=值</span></span><br><span class="line"><span class="comment"># 值由数据源名 + 表名组成，以小数点分隔。多个表以逗号分隔，支持 inline 表达式。</span></span><br><span class="line"><span class="comment"># &lt;table-name&gt;：逻辑表名</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_user.actual-data-nodes</span>=<span class="string">server-user.t_user</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order.actual-data-nodes</span>=<span class="string">server-order0.t_order0,server-order0.t_order1,server-order1.t_order0,server-order1.t_order1</span></span><br></pre></td></tr></table></figure>
<p>修改Order实体类的主键策略：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//@TableId(type = IdType.AUTO)//依赖数据库的主键自增策略</span></span><br><span class="line"><span class="meta">@TableId(type = IdType.ASSIGN_ID)</span><span class="comment">//分布式id</span></span><br></pre></td></tr></table></figure>
<p>测试：保留上面配置中的一个分片表节点分别进行测试，检查每个分片节点是否可用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 水平分片：插入数据测试</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testInsertOrder</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="type">Order</span> <span class="variable">order</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Order</span>();</span><br><span class="line">    order.setOrderNo(<span class="string">&quot;xiaofei001&quot;</span>);</span><br><span class="line">    order.setUserId(<span class="number">1L</span>);</span><br><span class="line">    order.setAmount(<span class="keyword">new</span> <span class="title class_">BigDecimal</span>(<span class="number">100</span>));</span><br><span class="line">    orderMapper.insert(order);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-4、行表达式"><a href="#2-4、行表达式" class="headerlink" title="2.4、行表达式"></a>2.4、行表达式</h3><p>优化上一步的分片表配置</p>
<p><a target="_blank" rel="noopener" href="https://shardingsphere.apache.org/document/5.1.1/cn/features/sharding/concept/inline-expression/">https://shardingsphere.apache.org/document/5.1.1/cn/features/sharding/concept/inline-expression/</a></p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#========================标准分片表配置（数据节点配置）</span></span><br><span class="line"><span class="comment"># spring.shardingsphere.rules.sharding.tables.&lt;table-name&gt;.actual-data-nodes=值</span></span><br><span class="line"><span class="comment"># 值由数据源名 + 表名组成，以小数点分隔。多个表以逗号分隔，支持 inline 表达式。</span></span><br><span class="line"><span class="comment"># &lt;table-name&gt;：逻辑表名</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_user.actual-data-nodes</span>=<span class="string">server-user.t_user</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order.actual-data-nodes</span>=<span class="string">server-order$-&gt;&#123;0..1&#125;.t_order$-&gt;&#123;0..1&#125;</span></span><br></pre></td></tr></table></figure>
<h3 id="2-5、分片算法配置"><a href="#2-5、分片算法配置" class="headerlink" title="2.5、分片算法配置"></a>2.5、分片算法配置</h3><p><strong>水平分库：</strong></p>
<p>分片规则：order表中<code>user_id</code>为偶数时，数据插入<code>server-order0服务器</code>，<code>user_id</code>为奇数时，数据插入<code>server-order1服务器</code>。这样分片的好处是，同一个用户的订单数据，一定会被插入到同一台服务器上，查询一个用户的订单时效率较高。</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#------------------------分库策略</span></span><br><span class="line"><span class="comment"># 分片列名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order.database-strategy.standard.sharding-column</span>=<span class="string">user_id</span></span><br><span class="line"><span class="comment"># 分片算法名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order.database-strategy.standard.sharding-algorithm-name</span>=<span class="string">alg_inline_userid</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">#------------------------分片算法配置</span></span><br><span class="line"><span class="comment"># 行表达式分片算法</span></span><br><span class="line"><span class="comment"># 分片算法类型</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.sharding-algorithms.alg_inline_userid.type</span>=<span class="string">INLINE</span></span><br><span class="line"><span class="comment"># 分片算法属性配置</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.sharding-algorithms.alg_inline_userid.props.algorithm-expression</span>=<span class="string">server-order$-&gt;&#123;user_id % 2&#125;</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 取模分片算法</span></span><br><span class="line"><span class="comment"># 分片算法类型</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.sharding-algorithms.alg_mod.type</span>=<span class="string">MOD</span></span><br><span class="line"><span class="comment"># 分片算法属性配置</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.sharding-algorithms.alg_mod.props.sharding-count</span>=<span class="string">2</span></span><br></pre></td></tr></table></figure>
<p>为了方便测试，先设置只在 <code>t_order0</code>表上进行测试</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">xxx.actual-data-nodes</span>=<span class="string">server-order$-&gt;&#123;0..1&#125;.t_order0</span></span><br></pre></td></tr></table></figure>
<p>测试：可以分别测试行表达式分片算法和取模分片算法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 水平分片：分库插入数据测试</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testInsertOrderDatabaseStrategy</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">long</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">4</span>; i++) &#123;</span><br><span class="line">        <span class="type">Order</span> <span class="variable">order</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Order</span>();</span><br><span class="line">        order.setOrderNo(<span class="string">&quot;xiaofei001&quot;</span>);</span><br><span class="line">        order.setUserId(i + <span class="number">1</span>);</span><br><span class="line">        order.setAmount(<span class="keyword">new</span> <span class="title class_">BigDecimal</span>(<span class="number">100</span>));</span><br><span class="line">        orderMapper.insert(order);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>水平分表：</strong></p>
<p>分片规则：order表中<code>order_no的哈希值为偶数时</code>，数据插入对应服务器的<code>t_order0表</code>，<code>order_no的哈希值为奇数时</code>，数据插入对应服务器的<code>t_order1表</code>。因为order_no是字符串形式，因此不能直接取模。</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#------------------------分表策略</span></span><br><span class="line"><span class="comment"># 分片列名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order.table-strategy.standard.sharding-column</span>=<span class="string">order_no</span></span><br><span class="line"><span class="comment"># 分片算法名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order.table-strategy.standard.sharding-algorithm-name</span>=<span class="string">alg_hash_mod</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">#------------------------分片算法配置</span></span><br><span class="line"><span class="comment"># 哈希取模分片算法</span></span><br><span class="line"><span class="comment"># 分片算法类型</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.sharding-algorithms.alg_hash_mod.type</span>=<span class="string">HASH_MOD</span></span><br><span class="line"><span class="comment"># 分片算法属性配置</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.sharding-algorithms.alg_hash_mod.props.sharding-count</span>=<span class="string">2</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>测试前不要忘记将如下节点改回原来的状态</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">xxx.actual-data-nodes</span>=<span class="string">server-order$-&gt;&#123;0..1&#125;.t_order$-&gt;&#123;0..1&#125;</span></span><br></pre></td></tr></table></figure>
<p>测试：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 水平分片：分表插入数据测试</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testInsertOrderTableStrategy</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">long</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">Order</span> <span class="variable">order</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Order</span>();</span><br><span class="line">        order.setOrderNo(<span class="string">&quot;xiaofei&quot;</span> + i);</span><br><span class="line">        order.setUserId(<span class="number">1L</span>);</span><br><span class="line">        order.setAmount(<span class="keyword">new</span> <span class="title class_">BigDecimal</span>(<span class="number">100</span>));</span><br><span class="line">        orderMapper.insert(order);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">long</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">5</span>; i &lt; <span class="number">9</span>; i++) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">Order</span> <span class="variable">order</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Order</span>();</span><br><span class="line">        order.setOrderNo(<span class="string">&quot;xiaofei&quot;</span> + i);</span><br><span class="line">        order.setUserId(<span class="number">2L</span>);</span><br><span class="line">        order.setAmount(<span class="keyword">new</span> <span class="title class_">BigDecimal</span>(<span class="number">100</span>));</span><br><span class="line">        orderMapper.insert(order);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 测试哈希取模</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testHash</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//注意hash取模的结果是整个字符串hash后再取模，和数值后缀是奇数还是偶数无关</span></span><br><span class="line">    System.out.println(<span class="string">&quot;xiaofei001&quot;</span>.hashCode() % <span class="number">2</span>);</span><br><span class="line">    System.out.println(<span class="string">&quot;xiaofei0011&quot;</span>.hashCode() % <span class="number">2</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>查询测试：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 水平分片：查询所有记录</span></span><br><span class="line"><span class="comment">     * 查询了两个数据源，每个数据源中使用UNION ALL连接两个表</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testShardingSelectAll</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    List&lt;Order&gt; orders = orderMapper.selectList(<span class="literal">null</span>);</span><br><span class="line">    orders.forEach(System.out::println);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 水平分片：根据user_id查询记录</span></span><br><span class="line"><span class="comment">     * 查询了一个数据源，每个数据源中使用UNION ALL连接两个表</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testShardingSelectByUserId</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    QueryWrapper&lt;Order&gt; orderQueryWrapper = <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>&lt;&gt;();</span><br><span class="line">    orderQueryWrapper.eq(<span class="string">&quot;user_id&quot;</span>, <span class="number">1L</span>);</span><br><span class="line">    List&lt;Order&gt; orders = orderMapper.selectList(orderQueryWrapper);</span><br><span class="line">    orders.forEach(System.out::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-6、分布式序列算法"><a href="#2-6、分布式序列算法" class="headerlink" title="2.6、分布式序列算法"></a>2.6、分布式序列算法</h3><p><strong>雪花算法：</strong></p>
<p><a target="_blank" rel="noopener" href="https://shardingsphere.apache.org/document/5.1.1/cn/features/sharding/concept/key-generator/">https://shardingsphere.apache.org/document/5.1.1/cn/features/sharding/concept/key-generator/</a></p>
<p>水平分片需要关注全局序列，因为不能简单的使用基于数据库的主键自增。</p>
<p>这里有两种方案：一种是基于MyBatisPlus的id策略；一种是ShardingSphere-JDBC的全局序列配置。</p>
<p><code>基于MyBatisPlus的id策略：</code>将Order类的id设置成如下形式</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@TableId(type = IdType.ASSIGN_ID)</span></span><br><span class="line"><span class="keyword">private</span> Long id;</span><br></pre></td></tr></table></figure>
<p><code>基于ShardingSphere-JDBC的全局序列配置</code>：和前面的MyBatisPlus的策略二选一</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#------------------------分布式序列策略配置</span></span><br><span class="line"><span class="comment"># 分布式序列列名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order.key-generate-strategy.column</span>=<span class="string">id</span></span><br><span class="line"><span class="comment"># 分布式序列算法名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order.key-generate-strategy.key-generator-name</span>=<span class="string">alg_snowflake</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 分布式序列算法配置</span></span><br><span class="line"><span class="comment"># 分布式序列算法类型</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.key-generators.alg_snowflake.type</span>=<span class="string">SNOWFLAKE</span></span><br><span class="line"><span class="comment"># 分布式序列算法属性配置</span></span><br><span class="line"><span class="comment">#spring.shardingsphere.rules.sharding.key-generators.alg_snowflake.props.xxx=</span></span><br></pre></td></tr></table></figure>
<p>此时，需要将实体类中的id策略修改成以下形式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//当配置了shardingsphere-jdbc的分布式序列时，自动使用shardingsphere-jdbc的分布式序列</span></span><br><span class="line"><span class="comment">//当没有配置shardingsphere-jdbc的分布式序列时，自动依赖数据库的主键自增策略</span></span><br><span class="line"><span class="meta">@TableId(type = IdType.AUTO)</span></span><br></pre></td></tr></table></figure>
<h2 id="3、多表关联"><a href="#3、多表关联" class="headerlink" title="3、多表关联"></a>3、多表关联</h2><h3 id="3-1、创建关联表"><a href="#3-1、创建关联表" class="headerlink" title="3.1、创建关联表"></a>3.1、创建关联表</h3><p>在<code>server-order0、server-order1</code>服务器中分别创建两张订单详情表<code>t_order_item0、t_order_item1</code></p>
<p>我们希望<code>同一个用户的订单表和订单详情表中的数据都在同一个数据源中，避免跨库关联</code>，因此这两张表我们使用相同的分片策略。</p>
<p>那么在<code>t_order_item</code>中我们也需要创建<code>order_no</code>和<code>user_id</code>这两个分片键</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> t_order_item0(</span><br><span class="line">    id <span class="type">BIGINT</span>,</span><br><span class="line">    order_no <span class="type">VARCHAR</span>(<span class="number">30</span>),</span><br><span class="line">    user_id <span class="type">BIGINT</span>,</span><br><span class="line">    price <span class="type">DECIMAL</span>(<span class="number">10</span>,<span class="number">2</span>),</span><br><span class="line">    `count` <span class="type">INT</span>,</span><br><span class="line">    <span class="keyword">PRIMARY</span> KEY(id)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> t_order_item1(</span><br><span class="line">    id <span class="type">BIGINT</span>,</span><br><span class="line">    order_no <span class="type">VARCHAR</span>(<span class="number">30</span>),</span><br><span class="line">    user_id <span class="type">BIGINT</span>,</span><br><span class="line">    price <span class="type">DECIMAL</span>(<span class="number">10</span>,<span class="number">2</span>),</span><br><span class="line">    `count` <span class="type">INT</span>,</span><br><span class="line">    <span class="keyword">PRIMARY</span> KEY(id)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h3 id="3-2、创建实体类"><a href="#3-2、创建实体类" class="headerlink" title="3.2、创建实体类"></a>3.2、创建实体类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo.entity;</span><br><span class="line"></span><br><span class="line"><span class="meta">@TableName(&quot;t_order_item&quot;)</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OrderItem</span> &#123;</span><br><span class="line">    <span class="comment">//当配置了shardingsphere-jdbc的分布式序列时，自动使用shardingsphere-jdbc的分布式序列</span></span><br><span class="line">    <span class="meta">@TableId(type = IdType.AUTO)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="keyword">private</span> String orderNo;</span><br><span class="line">    <span class="keyword">private</span> Long userId;</span><br><span class="line">    <span class="keyword">private</span> BigDecimal price;</span><br><span class="line">    <span class="keyword">private</span> Integer count;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3-3、创建Mapper"><a href="#3-3、创建Mapper" class="headerlink" title="3.3、创建Mapper"></a>3.3、创建Mapper</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shargingjdbcdemo.mapper;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Mapper</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">OrderItemMapper</span> <span class="keyword">extends</span> <span class="title class_">BaseMapper</span>&lt;OrderItem&gt; &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3-4、配置关联表"><a href="#3-4、配置关联表" class="headerlink" title="3.4、配置关联表"></a>3.4、配置关联表</h3><p>t_order_item的分片表、分片策略、分布式序列策略和t_order一致</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#------------------------标准分片表配置（数据节点配置）</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order_item.actual-data-nodes</span>=<span class="string">server-order$-&gt;&#123;0..1&#125;.t_order_item$-&gt;&#123;0..1&#125;</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">#------------------------分库策略</span></span><br><span class="line"><span class="comment"># 分片列名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order_item.database-strategy.standard.sharding-column</span>=<span class="string">user_id</span></span><br><span class="line"><span class="comment"># 分片算法名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order_item.database-strategy.standard.sharding-algorithm-name</span>=<span class="string">alg_mod</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">#------------------------分表策略</span></span><br><span class="line"><span class="comment"># 分片列名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order_item.table-strategy.standard.sharding-column</span>=<span class="string">order_no</span></span><br><span class="line"><span class="comment"># 分片算法名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order_item.table-strategy.standard.sharding-algorithm-name</span>=<span class="string">alg_hash_mod</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">#------------------------分布式序列策略配置</span></span><br><span class="line"><span class="comment"># 分布式序列列名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order_item.key-generate-strategy.column</span>=<span class="string">id</span></span><br><span class="line"><span class="comment"># 分布式序列算法名称</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_order_item.key-generate-strategy.key-generator-name</span>=<span class="string">alg_snowflake</span></span><br></pre></td></tr></table></figure>
<h3 id="3-5、测试插入数据"><a href="#3-5、测试插入数据" class="headerlink" title="3.5、测试插入数据"></a>3.5、测试插入数据</h3><p>同一个用户的订单表和订单详情表中的数据都在同一个数据源中，避免跨库关联</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 测试关联表插入</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testInsertOrderAndOrderItem</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">long</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt; <span class="number">3</span>; i++) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">Order</span> <span class="variable">order</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Order</span>();</span><br><span class="line">        order.setOrderNo(<span class="string">&quot;xiaofei&quot;</span> + i);</span><br><span class="line">        order.setUserId(<span class="number">1L</span>);</span><br><span class="line">        orderMapper.insert(order);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">long</span> <span class="variable">j</span> <span class="operator">=</span> <span class="number">1</span>; j &lt; <span class="number">3</span>; j++) &#123;</span><br><span class="line">            <span class="type">OrderItem</span> <span class="variable">orderItem</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">OrderItem</span>();</span><br><span class="line">            orderItem.setOrderNo(<span class="string">&quot;xiaofei&quot;</span> + i);</span><br><span class="line">            orderItem.setUserId(<span class="number">1L</span>);</span><br><span class="line">            orderItem.setPrice(<span class="keyword">new</span> <span class="title class_">BigDecimal</span>(<span class="number">10</span>));</span><br><span class="line">            orderItem.setCount(<span class="number">2</span>);</span><br><span class="line">            orderItemMapper.insert(orderItem);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">long</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">5</span>; i &lt; <span class="number">7</span>; i++) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">Order</span> <span class="variable">order</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Order</span>();</span><br><span class="line">        order.setOrderNo(<span class="string">&quot;xiaofei&quot;</span> + i);</span><br><span class="line">        order.setUserId(<span class="number">2L</span>);</span><br><span class="line">        orderMapper.insert(order);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">long</span> <span class="variable">j</span> <span class="operator">=</span> <span class="number">1</span>; j &lt; <span class="number">3</span>; j++) &#123;</span><br><span class="line">            <span class="type">OrderItem</span> <span class="variable">orderItem</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">OrderItem</span>();</span><br><span class="line">            orderItem.setOrderNo(<span class="string">&quot;xiaofei&quot;</span> + i);</span><br><span class="line">            orderItem.setUserId(<span class="number">2L</span>);</span><br><span class="line">            orderItem.setPrice(<span class="keyword">new</span> <span class="title class_">BigDecimal</span>(<span class="number">1</span>));</span><br><span class="line">            orderItem.setCount(<span class="number">3</span>);</span><br><span class="line">            orderItemMapper.insert(orderItem);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4、绑定表"><a href="#4、绑定表" class="headerlink" title="4、绑定表"></a>4、绑定表</h2><p><strong>需求：</strong>查询每个订单的订单号和总订单金额</p>
<h3 id="4-1、创建VO对象"><a href="#4-1、创建VO对象" class="headerlink" title="4.1、创建VO对象"></a>4.1、创建VO对象</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo.entity;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OrderVo</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String orderNo;</span><br><span class="line">    <span class="keyword">private</span> BigDecimal amount;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4-2、添加Mapper方法"><a href="#4-2、添加Mapper方法" class="headerlink" title="4.2、添加Mapper方法"></a>4.2、添加Mapper方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo.mapper;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Mapper</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">OrderMapper</span> <span class="keyword">extends</span> <span class="title class_">BaseMapper</span>&lt;Order&gt; &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Select(&#123;&quot;SELECT o.order_no, SUM(i.price * i.count) AS amount&quot;,</span></span><br><span class="line"><span class="meta">            &quot;FROM t_order o JOIN t_order_item i ON o.order_no = i.order_no&quot;,</span></span><br><span class="line"><span class="meta">            &quot;GROUP BY o.order_no&quot;&#125;)</span></span><br><span class="line">    List&lt;OrderVo&gt; <span class="title function_">getOrderAmount</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4-3、测试关联查询"><a href="#4-3、测试关联查询" class="headerlink" title="4.3、测试关联查询"></a>4.3、测试关联查询</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 测试关联表查询</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testGetOrderAmount</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    List&lt;OrderVo&gt; orderAmountList = orderMapper.getOrderAmount();</span><br><span class="line">    orderAmountList.forEach(System.out::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4-4、配置绑定表"><a href="#4-4、配置绑定表" class="headerlink" title="4.4、配置绑定表"></a>4.4、配置绑定表</h3><p>在原来水平分片配置的基础上添加如下配置：</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#------------------------绑定表</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.binding-tables[0]</span>=<span class="string">t_order,t_order_item</span></span><br></pre></td></tr></table></figure>
<p>配置完绑定表后再次进行关联查询的测试：</p>
<ul>
<li><p><strong>如果不配置绑定表：测试的结果为8个SQL。</strong>多表关联查询会出现笛卡尔积关联。</p>
</li>
<li><p><strong>如果配置绑定表：测试的结果为4个SQL。</strong> 多表关联查询不会出现笛卡尔积关联，关联查询效率将大大提升。</p>
</li>
</ul>
<p><code>绑定表：</code>指分片规则一致的一组分片表。 使用绑定表进行多表关联查询时，必须使用分片键进行关联，否则会出现笛卡尔积关联或跨库关联，从而影响查询效率。</p>
<h2 id="5、广播表"><a href="#5、广播表" class="headerlink" title="5、广播表"></a>5、广播表</h2><h3 id="4-1、什么是广播表"><a href="#4-1、什么是广播表" class="headerlink" title="4.1、什么是广播表"></a>4.1、什么是广播表</h3><p>指所有的分片数据源中都存在的表，表结构及其数据在每个数据库中均完全一致。 适用于数据量不大且需要与海量数据的表进行关联查询的场景，例如：字典表。</p>
<p>广播具有以下特性：</p>
<p>（1）插入、更新操作会实时在所有节点上执行，保持各个分片的数据一致性</p>
<p>（2）查询操作，只从一个节点获取</p>
<p>（3）可以跟任何一个表进行 JOIN 操作</p>
<h3 id="4-2、创建广播表"><a href="#4-2、创建广播表" class="headerlink" title="4.2、创建广播表"></a>4.2、创建广播表</h3><p>在server-order0、server-order1和server-user服务器中分别创建t_dict表</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> t_dict(</span><br><span class="line">    id <span class="type">BIGINT</span>,</span><br><span class="line">    dict_type <span class="type">VARCHAR</span>(<span class="number">200</span>),</span><br><span class="line">    <span class="keyword">PRIMARY</span> KEY(id)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h3 id="4-3、程序实现"><a href="#4-3、程序实现" class="headerlink" title="4.3、程序实现"></a>4.3、程序实现</h3><h4 id="4-3-1、创建实体类"><a href="#4-3-1、创建实体类" class="headerlink" title="4.3.1、创建实体类"></a>4.3.1、创建实体类</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo.entity;</span><br><span class="line"></span><br><span class="line"><span class="meta">@TableName(&quot;t_dict&quot;)</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Dict</span> &#123;</span><br><span class="line">    <span class="comment">//可以使用MyBatisPlus的雪花算法</span></span><br><span class="line">    <span class="meta">@TableId(type = IdType.ASSIGN_ID)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="keyword">private</span> String dictType;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="4-3-2、创建Mapper"><a href="#4-3-2、创建Mapper" class="headerlink" title="4.3.2、创建Mapper"></a>4.3.2、创建Mapper</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingjdbcdemo.mapper;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Mapper</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">DictMapper</span> <span class="keyword">extends</span> <span class="title class_">BaseMapper</span>&lt;Dict&gt; &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="4-3-3、配置广播表"><a href="#4-3-3、配置广播表" class="headerlink" title="4.3.3、配置广播表"></a>4.3.3、配置广播表</h4><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#数据节点可不配置，默认情况下，向所有数据源广播</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.tables.t_dict.actual-data-nodes</span>=<span class="string">server-user.t_dict,server-order$-&gt;&#123;0..1&#125;.t_dict</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"># 广播表</span></span><br><span class="line"><span class="attr">spring.shardingsphere.rules.sharding.broadcast-tables[0]</span>=<span class="string">t_dict</span></span><br></pre></td></tr></table></figure>
<h3 id="4-4、测试广播表"><a href="#4-4、测试广播表" class="headerlink" title="4.4、测试广播表"></a>4.4、测试广播表</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> DictMapper dictMapper;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 广播表：每个服务器中的t_dict同时添加了新数据</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testBroadcast</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="type">Dict</span> <span class="variable">dict</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Dict</span>();</span><br><span class="line">    dict.setDictType(<span class="string">&quot;type1&quot;</span>);</span><br><span class="line">    dictMapper.insert(dict);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查询操作，只从一个节点获取数据</span></span><br><span class="line"><span class="comment">     * 随机负载均衡规则</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testSelectBroadcast</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    List&lt;Dict&gt; dicts = dictMapper.selectList(<span class="literal">null</span>);</span><br><span class="line">    dicts.forEach(System.out::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="第07章-启动ShardingSphere-Proxy"><a href="#第07章-启动ShardingSphere-Proxy" class="headerlink" title="第07章 启动ShardingSphere-Proxy"></a>第07章 启动ShardingSphere-Proxy</h1><h2 id="1、获取"><a href="#1、获取" class="headerlink" title="1、获取"></a>1、获取</h2><p>目前 ShardingSphere-Proxy 提供了 3 种获取方式：</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://shardingsphere.apache.org/document/5.1.1/cn/user-manual/shardingsphere-proxy/startup/bin/">二进制发布包</a></li>
<li><a target="_blank" rel="noopener" href="https://shardingsphere.apache.org/document/5.1.1/cn/user-manual/shardingsphere-proxy/startup/docker/">Docker</a></li>
<li><a target="_blank" rel="noopener" href="https://shardingsphere.apache.org/document/5.1.1/cn/user-manual/shardingsphere-proxy/startup/helm/">Helm</a></li>
</ul>
<h2 id="2、使用二进制发布包安装"><a href="#2、使用二进制发布包安装" class="headerlink" title="2、使用二进制发布包安装"></a>2、使用二进制发布包安装</h2><p>二进制包既可以Linux系统运行，又可以在windows系统运行</p>
<p><strong>step1：解压二进制包</strong></p>
<p><code>apache-shardingsphere-5.1.1-shardingsphere-proxy-bin.tar.gz</code></p>
<p>windows：使用解压软件解压文件</p>
<p>Linux：将文件上传至/opt目录，并解压</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tar -zxvf apache-shardingsphere-5.1.1-shardingsphere-proxy-bin.tar.gz</span><br></pre></td></tr></table></figure>
<p><strong>step2：MySQL驱动</strong></p>
<p><code>mysql-connector-java-8.0.22.jar</code></p>
<p>将MySQl驱动放至解压目录中的<code>ext-lib</code>目录</p>
<p><strong>spte3：修改配置conf/server.yaml</strong></p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">rules:</span></span><br><span class="line">  <span class="bullet">-</span> <span class="type">!AUTHORITY</span></span><br><span class="line">    <span class="attr">users:</span></span><br><span class="line">      <span class="bullet">-</span> <span class="string">root@%:root</span></span><br><span class="line">    <span class="attr">provider:</span></span><br><span class="line">      <span class="attr">type:</span> <span class="string">ALL_PRIVILEGES_PERMITTED</span></span><br><span class="line"></span><br><span class="line"><span class="attr">props:</span></span><br><span class="line">  <span class="attr">sql-show:</span> <span class="literal">true</span></span><br></pre></td></tr></table></figure>
<p><strong>spte4：启动ShardingSphere-Proxy</strong></p>
<p>Linux 操作系统请运行 <code>bin/start.sh</code></p>
<p>Windows 操作系统请运行 <code>bin/start.bat</code> </p>
<p>指定端口号和配置文件目录：<code>bin/start.bat $&#123;proxy_port&#125; $&#123;proxy_conf_directory&#125;</code> </p>
<p><strong>step5：远程连接ShardingSphere-Proxy</strong></p>
<p>远程访问</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mysql -h192.168.100.1 -P3307 -uroot -p</span><br></pre></td></tr></table></figure>
<p><strong>step6：访问测试</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">show</span> databases;</span><br></pre></td></tr></table></figure>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220819152009158.png" alt="image-20220819152009158"></p>
<h2 id="3、使用Docker安装"><a href="#3、使用Docker安装" class="headerlink" title="3、使用Docker安装"></a>3、使用Docker安装</h2><p><strong>step1：启动Docker容器</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">docker run -d \</span><br><span class="line">-v /xiaofei/server/proxy-a/conf:/opt/shardingsphere-proxy/conf \</span><br><span class="line">-v /xiaofei/server/proxy-a/ext-lib:/opt/shardingsphere-proxy/ext-lib \</span><br><span class="line">-e ES_JAVA_OPTS=&quot;-Xmx256m -Xms256m -Xmn128m&quot; \</span><br><span class="line">-p 3321:3307 \</span><br><span class="line">--name server-proxy-a \</span><br><span class="line">apache/shardingsphere-proxy:5.1.1</span><br></pre></td></tr></table></figure>
<p><strong>step2：上传MySQL驱动</strong></p>
<p>将MySQl驱动上传至<code>/xiaofei/server/proxy-a/ext-lib</code>目录</p>
<p><strong>spte3：修改配置server.yaml</strong></p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">rules:</span></span><br><span class="line">  <span class="bullet">-</span> <span class="type">!AUTHORITY</span></span><br><span class="line">    <span class="attr">users:</span></span><br><span class="line">      <span class="bullet">-</span> <span class="string">root@%:root</span></span><br><span class="line">    <span class="attr">provider:</span></span><br><span class="line">      <span class="attr">type:</span> <span class="string">ALL_PRIVILEGES_PERMITTED</span></span><br><span class="line"></span><br><span class="line"><span class="attr">props:</span></span><br><span class="line">  <span class="attr">sql-show:</span> <span class="literal">true</span></span><br></pre></td></tr></table></figure>
<p>将配置文件上传至<code>/xiaofei/server/proxy-a/conf</code>目录</p>
<p><strong>spte4：重启容器</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker restart server-proxy-a</span><br></pre></td></tr></table></figure>
<p><strong>step5：远程连接ShardingSphere-Proxy</strong></p>
<p>ShardingSphere-Proxy容器中默认情况下没有mysql命令行客户端的安装，因此需要远程访问</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mysql -h192.168.100.201 -P3321 -uroot -p</span><br></pre></td></tr></table></figure>
<p><strong>step6：访问测试</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">show</span> databases;</span><br></pre></td></tr></table></figure>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220819152009158.png" alt="image-20220819152009158"></p>
<p><strong>常见问题：docker容器无法远程连接</strong></p>
<p>容器可以成功的创建并启动，但是无法远程连接。排除防火墙和网络等问题后，看看是不是因为容器内存不足导致。</p>
<p><code>原因：</code>容器可分配内存不足</p>
<p><code>查看办法：</code>进入容器后查看ShardingSphere-Proxy的日志，如有有<code>cannot allocate memory</code>，则说明容器内存不足</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">docker exec -it server-proxy-a env LANG=C.UTF-8 /bin/bash</span><br><span class="line">cd /opt/shardingsphere-proxy/logs</span><br><span class="line">tail stdout.log </span><br></pre></td></tr></table></figure>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20220819151154763.png" alt="image-20220819151154763"></p>
<p><code>解决方案：</code>创建容器的时候使用JVM参数</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">-e ES_JAVA_OPTS=&quot;-Xmx256m -Xms256m -Xmn128m&quot;</span><br></pre></td></tr></table></figure>
<h1 id="第08章-ShardingSphere-Proxy读写分离"><a href="#第08章-ShardingSphere-Proxy读写分离" class="headerlink" title="第08章 ShardingSphere-Proxy读写分离"></a>第08章 ShardingSphere-Proxy读写分离</h1><h2 id="1、修改配置文件"><a href="#1、修改配置文件" class="headerlink" title="1、修改配置文件"></a>1、修改配置文件</h2><p><strong>修改配置config-readwrite-splitting.yaml</strong></p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">schemaName:</span> <span class="string">readwrite_splitting_db</span></span><br><span class="line"></span><br><span class="line"><span class="attr">dataSources:</span></span><br><span class="line">  <span class="attr">write_ds:</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">jdbc:mysql://192.168.100.201:3306/db_user?serverTimezone=UTC&amp;useSSL=false</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">password:</span> <span class="number">123456</span></span><br><span class="line">    <span class="attr">connectionTimeoutMilliseconds:</span> <span class="number">30000</span></span><br><span class="line">    <span class="attr">idleTimeoutMilliseconds:</span> <span class="number">60000</span></span><br><span class="line">    <span class="attr">maxLifetimeMilliseconds:</span> <span class="number">1800000</span></span><br><span class="line">    <span class="attr">maxPoolSize:</span> <span class="number">50</span></span><br><span class="line">    <span class="attr">minPoolSize:</span> <span class="number">1</span></span><br><span class="line">  <span class="attr">read_ds_0:</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">jdbc:mysql://192.168.100.201:3307/db_user?serverTimezone=UTC&amp;useSSL=false</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">password:</span> <span class="number">123456</span></span><br><span class="line">    <span class="attr">connectionTimeoutMilliseconds:</span> <span class="number">30000</span></span><br><span class="line">    <span class="attr">idleTimeoutMilliseconds:</span> <span class="number">60000</span></span><br><span class="line">    <span class="attr">maxLifetimeMilliseconds:</span> <span class="number">1800000</span></span><br><span class="line">    <span class="attr">maxPoolSize:</span> <span class="number">50</span></span><br><span class="line">    <span class="attr">minPoolSize:</span> <span class="number">1</span></span><br><span class="line">  <span class="attr">read_ds_1:</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">jdbc:mysql://192.168.100.201:3308/db_user?serverTimezone=UTC&amp;useSSL=false</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">password:</span> <span class="number">123456</span></span><br><span class="line">    <span class="attr">connectionTimeoutMilliseconds:</span> <span class="number">30000</span></span><br><span class="line">    <span class="attr">idleTimeoutMilliseconds:</span> <span class="number">60000</span></span><br><span class="line">    <span class="attr">maxLifetimeMilliseconds:</span> <span class="number">1800000</span></span><br><span class="line">    <span class="attr">maxPoolSize:</span> <span class="number">50</span></span><br><span class="line">    <span class="attr">minPoolSize:</span> <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="attr">rules:</span></span><br><span class="line"><span class="bullet">-</span> <span class="type">!READWRITE_SPLITTING</span></span><br><span class="line">  <span class="attr">dataSources:</span></span><br><span class="line">    <span class="attr">readwrite_ds:</span></span><br><span class="line">      <span class="attr">type:</span> <span class="string">Static</span></span><br><span class="line">      <span class="attr">props:</span></span><br><span class="line">        <span class="attr">write-data-source-name:</span> <span class="string">write_ds</span></span><br><span class="line">        <span class="attr">read-data-source-names:</span> <span class="string">read_ds_0,read_ds_1</span></span><br></pre></td></tr></table></figure>
<p>将配置文件上传至<code>/xiaofei/server/proxy-a/conf</code>目录</p>
<p><strong>重启容器</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker restart server-proxy-a</span><br></pre></td></tr></table></figure>
<h2 id="2、实时查看日志"><a href="#2、实时查看日志" class="headerlink" title="2、实时查看日志"></a>2、实时查看日志</h2><p>可以通过这种方式查看服务器中输出的SQL语句</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">docker exec -it server-proxy-a env LANG=C.UTF-8 /bin/bash</span><br><span class="line">tail -f /opt/shardingsphere-proxy/logs/stdout.log </span><br></pre></td></tr></table></figure>
<h2 id="3、远程访问测试"><a href="#3、远程访问测试" class="headerlink" title="3、远程访问测试"></a>3、远程访问测试</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">show</span> databases;</span><br><span class="line">mysql<span class="operator">&gt;</span> use readwrite_splitting_db;</span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">show</span> tables;</span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> t_user;</span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> t_user;</span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> t_user(uname) <span class="keyword">values</span>(<span class="string">&#x27;wang5&#x27;</span>);</span><br></pre></td></tr></table></figure>
<h2 id="4、应用程序访问Proxy"><a href="#4、应用程序访问Proxy" class="headerlink" title="4、应用程序访问Proxy"></a>4、应用程序访问Proxy</h2><h3 id="4-1、创建项目"><a href="#4-1、创建项目" class="headerlink" title="4.1、创建项目"></a>4.1、创建项目</h3><p>项目类型：Spring Initializr</p>
<p>SpringBoot脚手架：<a target="_blank" rel="noopener" href="http://start.aliyun.com">http://start.aliyun.com</a></p>
<p>项目名：sharding-proxy-demo</p>
<p>SpringBoot版本：2.3.7.RELEASE</p>
<h3 id="4-2、添加依赖"><a href="#4-2、添加依赖" class="headerlink" title="4.2、添加依赖"></a>4.2、添加依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">scope</span>&gt;</span>runtime<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.3.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">exclusions</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">exclusion</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.junit.vintage<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>junit-vintage-engine<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">exclusion</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">exclusions</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="4-3、创建实体类"><a href="#4-3、创建实体类" class="headerlink" title="4.3、创建实体类"></a>4.3、创建实体类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingproxydemo.entity;</span><br><span class="line"></span><br><span class="line"><span class="meta">@TableName(&quot;t_user&quot;)</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line">    <span class="meta">@TableId(type = IdType.AUTO)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="keyword">private</span> String uname;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="4-4、创建Mapper"><a href="#4-4、创建Mapper" class="headerlink" title="4.4、创建Mapper"></a>4.4、创建Mapper</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingproxydemo.mapper;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Mapper</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserMapper</span> <span class="keyword">extends</span> <span class="title class_">BaseMapper</span>&lt;User&gt; &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4-5、配置数据源"><a href="#4-5、配置数据源" class="headerlink" title="4.5、配置数据源"></a>4.5、配置数据源</h3><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 应用名称</span></span><br><span class="line"><span class="attr">spring.application.name</span>=<span class="string">sharding-proxy-demo</span></span><br><span class="line"><span class="comment"># 开发环境设置</span></span><br><span class="line"><span class="attr">spring.profiles.active</span>=<span class="string">dev</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">#mysql数据库连接（proxy）</span></span><br><span class="line"><span class="attr">spring.datasource.driver-class-name</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">spring.datasource.url</span>=<span class="string">jdbc:mysql://192.168.100.201:3321/readwrite_splitting_db?serverTimezone=GMT%2B8&amp;useSSL=false</span></span><br><span class="line"><span class="attr">spring.datasource.username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">spring.datasource.password</span>=<span class="string">root</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">#mybatis日志</span></span><br><span class="line"><span class="attr">mybatis-plus.configuration.log-impl</span>=<span class="string">org.apache.ibatis.logging.stdout.StdOutImpl</span></span><br></pre></td></tr></table></figure>
<h3 id="4-6、测试"><a href="#4-6、测试" class="headerlink" title="4.6、测试"></a>4.6、测试</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.shardingproxydemo;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ShardingProxyDemoApplicationTests</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 读数据测试</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testSelectAll</span><span class="params">()</span>&#123;</span><br><span class="line">        List&lt;User&gt; users = userMapper.selectList(<span class="literal">null</span>);</span><br><span class="line">        users.forEach(System.out::println);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="第09章-ShardingSphere-Proxy垂直分片"><a href="#第09章-ShardingSphere-Proxy垂直分片" class="headerlink" title="第09章 ShardingSphere-Proxy垂直分片"></a>第09章 ShardingSphere-Proxy垂直分片</h1><h2 id="1、修改配置文件-1"><a href="#1、修改配置文件-1" class="headerlink" title="1、修改配置文件"></a>1、修改配置文件</h2><p><strong>修改配置config-sharding.yaml</strong></p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">schemaName:</span> <span class="string">sharding_db</span></span><br><span class="line"></span><br><span class="line"><span class="attr">dataSources:</span></span><br><span class="line">  <span class="attr">ds_0:</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">jdbc:mysql://192.168.100.201:3301/db_user?serverTimezone=UTC&amp;useSSL=false</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">password:</span> <span class="number">123456</span></span><br><span class="line">    <span class="attr">connectionTimeoutMilliseconds:</span> <span class="number">30000</span></span><br><span class="line">    <span class="attr">idleTimeoutMilliseconds:</span> <span class="number">60000</span></span><br><span class="line">    <span class="attr">maxLifetimeMilliseconds:</span> <span class="number">1800000</span></span><br><span class="line">    <span class="attr">maxPoolSize:</span> <span class="number">50</span></span><br><span class="line">    <span class="attr">minPoolSize:</span> <span class="number">1</span></span><br><span class="line">  <span class="attr">ds_1:</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">jdbc:mysql://192.168.100.201:3302/db_order?serverTimezone=UTC&amp;useSSL=false</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">password:</span> <span class="number">123456</span></span><br><span class="line">    <span class="attr">connectionTimeoutMilliseconds:</span> <span class="number">30000</span></span><br><span class="line">    <span class="attr">idleTimeoutMilliseconds:</span> <span class="number">60000</span></span><br><span class="line">    <span class="attr">maxLifetimeMilliseconds:</span> <span class="number">1800000</span></span><br><span class="line">    <span class="attr">maxPoolSize:</span> <span class="number">50</span></span><br><span class="line">    <span class="attr">minPoolSize:</span> <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="attr">rules:</span></span><br><span class="line"><span class="bullet">-</span> <span class="type">!SHARDING</span></span><br><span class="line">  <span class="attr">tables:</span></span><br><span class="line">    <span class="attr">t_user:</span></span><br><span class="line">      <span class="attr">actualDataNodes:</span> <span class="string">ds_0.t_user</span></span><br><span class="line">    <span class="attr">t_order:</span></span><br><span class="line">      <span class="attr">actualDataNodes:</span> <span class="string">ds_1.t_order</span></span><br></pre></td></tr></table></figure>
<h2 id="2、实时查看日志-1"><a href="#2、实时查看日志-1" class="headerlink" title="2、实时查看日志"></a>2、实时查看日志</h2><p>可以通过这种方式查看服务器中输出的SQL语句</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">docker exec -it server-proxy-a env LANG=C.UTF-8 /bin/bash</span><br><span class="line">tail -f /opt/shardingsphere-proxy/logs/stdout.log </span><br></pre></td></tr></table></figure>
<h2 id="3、远程访问测试-1"><a href="#3、远程访问测试-1" class="headerlink" title="3、远程访问测试"></a>3、远程访问测试</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">show</span> databases;</span><br><span class="line">mysql<span class="operator">&gt;</span> use sharding_db;</span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">show</span> tables;</span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> t_order;</span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> t_user;</span><br></pre></td></tr></table></figure>
<h1 id="第10章-ShardingSphere-Proxy水平分片"><a href="#第10章-ShardingSphere-Proxy水平分片" class="headerlink" title="第10章 ShardingSphere-Proxy水平分片"></a>第10章 ShardingSphere-Proxy水平分片</h1><h2 id="1、修改配置文件-2"><a href="#1、修改配置文件-2" class="headerlink" title="1、修改配置文件"></a>1、修改配置文件</h2><p><strong>修改配置config-sharding.yaml</strong></p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">schemaName:</span> <span class="string">sharding_db</span></span><br><span class="line"></span><br><span class="line"><span class="attr">dataSources:</span></span><br><span class="line">  <span class="attr">ds_user:</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">jdbc:mysql://192.168.100.201:3301/db_user?serverTimezone=UTC&amp;useSSL=false</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">password:</span> <span class="number">123456</span></span><br><span class="line">    <span class="attr">connectionTimeoutMilliseconds:</span> <span class="number">30000</span></span><br><span class="line">    <span class="attr">idleTimeoutMilliseconds:</span> <span class="number">60000</span></span><br><span class="line">    <span class="attr">maxLifetimeMilliseconds:</span> <span class="number">1800000</span></span><br><span class="line">    <span class="attr">maxPoolSize:</span> <span class="number">50</span></span><br><span class="line">    <span class="attr">minPoolSize:</span> <span class="number">1</span></span><br><span class="line">  <span class="attr">ds_order0:</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">jdbc:mysql://192.168.100.201:3310/db_order?serverTimezone=UTC&amp;useSSL=false</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">password:</span> <span class="number">123456</span></span><br><span class="line">    <span class="attr">connectionTimeoutMilliseconds:</span> <span class="number">30000</span></span><br><span class="line">    <span class="attr">idleTimeoutMilliseconds:</span> <span class="number">60000</span></span><br><span class="line">    <span class="attr">maxLifetimeMilliseconds:</span> <span class="number">1800000</span></span><br><span class="line">    <span class="attr">maxPoolSize:</span> <span class="number">50</span></span><br><span class="line">    <span class="attr">minPoolSize:</span> <span class="number">1</span></span><br><span class="line">  <span class="attr">ds_order1:</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">jdbc:mysql://192.168.100.201:3311/db_order?serverTimezone=UTC&amp;useSSL=false</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">password:</span> <span class="number">123456</span></span><br><span class="line">    <span class="attr">connectionTimeoutMilliseconds:</span> <span class="number">30000</span></span><br><span class="line">    <span class="attr">idleTimeoutMilliseconds:</span> <span class="number">60000</span></span><br><span class="line">    <span class="attr">maxLifetimeMilliseconds:</span> <span class="number">1800000</span></span><br><span class="line">    <span class="attr">maxPoolSize:</span> <span class="number">50</span></span><br><span class="line">    <span class="attr">minPoolSize:</span> <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="attr">rules:</span></span><br><span class="line"><span class="bullet">-</span> <span class="type">!SHARDING</span></span><br><span class="line">  <span class="attr">tables:</span></span><br><span class="line">    <span class="attr">t_user:</span></span><br><span class="line">      <span class="attr">actualDataNodes:</span> <span class="string">ds_user.t_user</span></span><br><span class="line"></span><br><span class="line">    <span class="attr">t_order:</span></span><br><span class="line">      <span class="attr">actualDataNodes:</span> <span class="string">ds_order$&#123;0..1&#125;.t_order$&#123;0..1&#125;</span></span><br><span class="line">      <span class="attr">databaseStrategy:</span></span><br><span class="line">        <span class="attr">standard:</span></span><br><span class="line">          <span class="attr">shardingColumn:</span> <span class="string">user_id</span></span><br><span class="line">          <span class="attr">shardingAlgorithmName:</span> <span class="string">alg_mod</span></span><br><span class="line">      <span class="attr">tableStrategy:</span></span><br><span class="line">        <span class="attr">standard:</span></span><br><span class="line">          <span class="attr">shardingColumn:</span> <span class="string">order_no</span></span><br><span class="line">          <span class="attr">shardingAlgorithmName:</span> <span class="string">alg_hash_mod</span></span><br><span class="line">      <span class="attr">keyGenerateStrategy:</span></span><br><span class="line">        <span class="attr">column:</span> <span class="string">id</span></span><br><span class="line">        <span class="attr">keyGeneratorName:</span> <span class="string">snowflake</span></span><br><span class="line">    <span class="attr">t_order_item:</span></span><br><span class="line">      <span class="attr">actualDataNodes:</span> <span class="string">ds_order$&#123;0..1&#125;.t_order_item$&#123;0..1&#125;</span></span><br><span class="line">      <span class="attr">databaseStrategy:</span></span><br><span class="line">        <span class="attr">standard:</span></span><br><span class="line">          <span class="attr">shardingColumn:</span> <span class="string">user_id</span></span><br><span class="line">          <span class="attr">shardingAlgorithmName:</span> <span class="string">alg_mod</span></span><br><span class="line">      <span class="attr">tableStrategy:</span></span><br><span class="line">        <span class="attr">standard:</span></span><br><span class="line">          <span class="attr">shardingColumn:</span> <span class="string">order_no</span></span><br><span class="line">          <span class="attr">shardingAlgorithmName:</span> <span class="string">alg_hash_mod</span></span><br><span class="line">      <span class="attr">keyGenerateStrategy:</span></span><br><span class="line">        <span class="attr">column:</span> <span class="string">id</span></span><br><span class="line">        <span class="attr">keyGeneratorName:</span> <span class="string">snowflake</span></span><br><span class="line"></span><br><span class="line">  <span class="attr">bindingTables:</span></span><br><span class="line">    <span class="bullet">-</span> <span class="string">t_order,t_order_item</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="attr">broadcastTables:</span></span><br><span class="line">    <span class="bullet">-</span> <span class="string">t_dict</span></span><br><span class="line"></span><br><span class="line">  <span class="attr">shardingAlgorithms:</span></span><br><span class="line">    <span class="attr">alg_inline_userid:</span></span><br><span class="line">      <span class="attr">type:</span> <span class="string">INLINE</span></span><br><span class="line">      <span class="attr">props:</span></span><br><span class="line">        <span class="attr">algorithm-expression:</span> <span class="string">server-order$-&gt;&#123;user_id</span> <span class="string">%</span> <span class="number">2</span><span class="string">&#125;</span></span><br><span class="line">    <span class="attr">alg_mod:</span></span><br><span class="line">      <span class="attr">type:</span> <span class="string">MOD</span></span><br><span class="line">      <span class="attr">props:</span></span><br><span class="line">        <span class="attr">sharding-count:</span> <span class="number">2</span></span><br><span class="line">    <span class="attr">alg_hash_mod:</span></span><br><span class="line">      <span class="attr">type:</span> <span class="string">HASH_MOD</span></span><br><span class="line">      <span class="attr">props:</span></span><br><span class="line">        <span class="attr">sharding-count:</span> <span class="number">2</span></span><br><span class="line">  </span><br><span class="line">  <span class="attr">keyGenerators:</span></span><br><span class="line">    <span class="attr">snowflake:</span></span><br><span class="line">      <span class="attr">type:</span> <span class="string">SNOWFLAKE</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="2、实时查看日志-2"><a href="#2、实时查看日志-2" class="headerlink" title="2、实时查看日志"></a>2、实时查看日志</h2><p>可以通过这种方式查看服务器中输出的SQL语句</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">docker exec -it server-proxy-a env LANG=C.UTF-8 /bin/bash</span><br><span class="line">tail -f /opt/shardingsphere-proxy/logs/stdout.log </span><br></pre></td></tr></table></figure>
<h2 id="3、远程访问测试-2"><a href="#3、远程访问测试-2" class="headerlink" title="3、远程访问测试"></a>3、远程访问测试</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">show</span> databases;</span><br><span class="line">mysql<span class="operator">&gt;</span> use sharding_db;</span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">show</span> tables;</span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> t_order; <span class="comment">--测试水平分片</span></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> t_dict; <span class="comment">--测试广播表</span></span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__title"><span class="post-copyright-info"><h>SpringBoot使用ShardingSphere</h></span></div><div class="post-copyright__type"><span class="post-copyright-info"><a href="https://www.naste.top:1024/posts/2343814370.html">https://www.naste.top:1024/posts/2343814370.html</a></span></div><div class="post-copyright-m"><div class="post-copyright-m-info"><div class="post-copyright-a"><h>作者</h><div class="post-copyright-cc-info"><h>XiaoFei🥝</h></div></div><div class="post-copyright-c"><h>发布于</h><div class="post-copyright-cc-info"><h>2023-08-17</h></div></div><div class="post-copyright-u"><h>更新于</h><div class="post-copyright-cc-info"><h>2024-04-26</h></div></div><div class="post-copyright-c"><h>许可协议</h><div class="post-copyright-cc-info"><a class="icon" rel="noopener" target="_blank" title="Creative Commons" href="https://creativecommons.org/"><i class="fab fa-creative-commons"></i></a><a rel="noopener" target="_blank" title="CC BY-NC-SA 4.0" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a></div></div></div></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>Java</a><a class="post-meta__tags" href="/tags/MySQL/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>MySQL</a><a class="post-meta__tags" href="/tags/SpringBoot/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>SpringBoot</a><a class="post-meta__tags" href="/tags/ShardingSphere/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>ShardingSphere</a></div></div><link rel="stylesheet" href="/css/coin.css" media="defer" onload="this.media='all'"/><div class="post-reward"><button class="tip-button reward-button"><span class="tip-button__text">投喂作者</span><div class="coin-wrapper"><div class="coin"><div class="coin__middle"></div><div class="coin__back"></div><div class="coin__front"></div></div></div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://www.naste.top:9000/images/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://www.naste.top:9000/images/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://www.naste.top:9000/images/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://www.naste.top:9000/images/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></button></div><audio id="coinAudio" src="https://npm.elemecdn.com/akilar-candyassets@1.0.36/audio/aowu.m4a"></audio><script defer="defer" src="/js/coin.js"></script><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/3180172769.html"><img class="prev-cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678368263.webp" onerror="onerror=null;src='/assets/r2.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">统一认证授权中心</div></div></a></div><div class="next-post pull-right"><a href="/posts/3224676358.html"><img class="next-cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678368264.webp" onerror="onerror=null;src='/assets/r2.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">SpringBoot使用Hutool实现数据脱敏</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/2414116852.html" title="JDBC"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1515952743784.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">JDBC</div></div></a></div><div><a href="/posts/4265763703.html" title="使用Spring Session解决分布式Session共享问题"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1671882661.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">使用Spring Session解决分布式Session共享问题</div></div></a></div><div><a href="/posts/3041119952.html" title="RabbitMQ"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678672812.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">RabbitMQ</div></div></a></div><div><a href="/posts/1154747761.html" title="代码生成器项目解读"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678368249.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">代码生成器项目解读</div></div></a></div><div><a href="/posts/2510331546.html" title="SpringBoot3响应式编程"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1671882662.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">SpringBoot3响应式编程</div></div></a></div><div><a href="/posts/3528284937.html" title="SpringBoot自定义注解使用"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1671882685.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">SpringBoot自定义注解使用</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><svg class="meta_icon" style="width:22px;height:22px;position:relative;top:5px"><use xlink:href="#icon-mulu1"></use></svg><span style="font-weight:bold">目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%9B%AE%E5%BD%95"><span class="toc-text">目录</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC01%E7%AB%A0-%E9%AB%98%E6%80%A7%E8%83%BD%E6%9E%B6%E6%9E%84%E6%A8%A1%E5%BC%8F"><span class="toc-text">第01章 高性能架构模式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E8%AF%BB%E5%86%99%E5%88%86%E7%A6%BB%E6%9E%B6%E6%9E%84"><span class="toc-text">1、读写分离架构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E6%95%B0%E6%8D%AE%E5%BA%93%E5%88%86%E7%89%87%E6%9E%B6%E6%9E%84"><span class="toc-text">2、数据库分片架构</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1%E3%80%81%E5%9E%82%E7%9B%B4%E5%88%86%E7%89%87"><span class="toc-text">2.1、垂直分片</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2%E3%80%81%E6%B0%B4%E5%B9%B3%E5%88%86%E7%89%87"><span class="toc-text">2.2、水平分片</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E8%AF%BB%E5%86%99%E5%88%86%E7%A6%BB%E5%92%8C%E6%95%B0%E6%8D%AE%E5%88%86%E7%89%87%E6%9E%B6%E6%9E%84"><span class="toc-text">3、读写分离和数据分片架构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F"><span class="toc-text">4、实现方式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1%E3%80%81%E7%A8%8B%E5%BA%8F%E4%BB%A3%E7%A0%81%E5%B0%81%E8%A3%85"><span class="toc-text">4.1、程序代码封装</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2%E3%80%81%E4%B8%AD%E9%97%B4%E4%BB%B6%E5%B0%81%E8%A3%85"><span class="toc-text">4.2、中间件封装</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3%E3%80%81%E5%B8%B8%E7%94%A8%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="toc-text">4.3、常用解决方案</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC02%E7%AB%A0-ShardingSphere"><span class="toc-text">第02章 ShardingSphere</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E7%AE%80%E4%BB%8B"><span class="toc-text">1、简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81ShardingSphere-JDBC"><span class="toc-text">2、ShardingSphere-JDBC</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81ShardingSphere-Proxy"><span class="toc-text">3、ShardingSphere-Proxy</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC03%E7%AB%A0-MySQL%E4%B8%BB%E4%BB%8E%E5%90%8C%E6%AD%A5"><span class="toc-text">第03章 MySQL主从同步</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81MySQL%E4%B8%BB%E4%BB%8E%E5%90%8C%E6%AD%A5%E5%8E%9F%E7%90%86"><span class="toc-text">1、MySQL主从同步原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E4%B8%80%E4%B8%BB%E5%A4%9A%E4%BB%8E%E9%85%8D%E7%BD%AE"><span class="toc-text">2、一主多从配置</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1%E3%80%81%E5%87%86%E5%A4%87%E4%B8%BB%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="toc-text">2.1、准备主服务器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2%E3%80%81%E5%87%86%E5%A4%87%E4%BB%8E%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="toc-text">2.2、准备从服务器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3%E3%80%81%E5%90%AF%E5%8A%A8%E4%B8%BB%E4%BB%8E%E5%90%8C%E6%AD%A5"><span class="toc-text">2.3、启动主从同步</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4%E3%80%81%E5%AE%9E%E7%8E%B0%E4%B8%BB%E4%BB%8E%E5%90%8C%E6%AD%A5"><span class="toc-text">2.4、实现主从同步</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-5%E3%80%81%E5%81%9C%E6%AD%A2%E5%92%8C%E9%87%8D%E7%BD%AE"><span class="toc-text">2.5、停止和重置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-6%E3%80%81%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98"><span class="toc-text">2.6、常见问题</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%97%AE%E9%A2%981"><span class="toc-text">问题1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%97%AE%E9%A2%982"><span class="toc-text">问题2</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC04%E7%AB%A0-ShardingSphere-JDBC%E8%AF%BB%E5%86%99%E5%88%86%E7%A6%BB"><span class="toc-text">第04章 ShardingSphere-JDBC读写分离</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E5%88%9B%E5%BB%BASpringBoot%E7%A8%8B%E5%BA%8F"><span class="toc-text">1、创建SpringBoot程序</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1%E3%80%81%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE"><span class="toc-text">1.1、创建项目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2%E3%80%81%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96"><span class="toc-text">1.2、添加依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3%E3%80%81%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BD%93%E7%B1%BB"><span class="toc-text">1.3、创建实体类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-4%E3%80%81%E5%88%9B%E5%BB%BAMapper"><span class="toc-text">1.4、创建Mapper</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-5%E3%80%81%E9%85%8D%E7%BD%AE%E8%AF%BB%E5%86%99%E5%88%86%E7%A6%BB"><span class="toc-text">1.5、配置读写分离</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E6%B5%8B%E8%AF%95"><span class="toc-text">2、测试</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1%E3%80%81%E8%AF%BB%E5%86%99%E5%88%86%E7%A6%BB%E6%B5%8B%E8%AF%95"><span class="toc-text">2.1、读写分离测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2%E3%80%81%E4%BA%8B%E5%8A%A1%E6%B5%8B%E8%AF%95"><span class="toc-text">2.2、事务测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3%E3%80%81%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E6%B5%8B%E8%AF%95"><span class="toc-text">2.3、负载均衡测试</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC05%E7%AB%A0-ShardingSphere-JDBC%E5%9E%82%E7%9B%B4%E5%88%86%E7%89%87"><span class="toc-text">第05章 ShardingSphere-JDBC垂直分片</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E5%87%86%E5%A4%87%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="toc-text">1、准备服务器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1%E3%80%81%E5%88%9B%E5%BB%BAserver-user%E5%AE%B9%E5%99%A8"><span class="toc-text">1.1、创建server-user容器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2%E3%80%81%E5%88%9B%E5%BB%BAserver-order%E5%AE%B9%E5%99%A8"><span class="toc-text">1.2、创建server-order容器</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E7%A8%8B%E5%BA%8F%E5%AE%9E%E7%8E%B0"><span class="toc-text">2、程序实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BD%93%E7%B1%BB"><span class="toc-text">2.1、创建实体类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2%E3%80%81%E5%88%9B%E5%BB%BAMapper"><span class="toc-text">2.2、创建Mapper</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3%E3%80%81%E9%85%8D%E7%BD%AE%E5%9E%82%E7%9B%B4%E5%88%86%E7%89%87"><span class="toc-text">2.3、配置垂直分片</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E6%B5%8B%E8%AF%95%E5%9E%82%E7%9B%B4%E5%88%86%E7%89%87"><span class="toc-text">3、测试垂直分片</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E8%A7%81%E9%94%99%E8%AF%AF"><span class="toc-text">常见错误</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC06%E7%AB%A0-ShardingSphere-JDBC%E6%B0%B4%E5%B9%B3%E5%88%86%E7%89%87"><span class="toc-text">第06章 ShardingSphere-JDBC水平分片</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E5%87%86%E5%A4%87%E6%9C%8D%E5%8A%A1%E5%99%A8-1"><span class="toc-text">1、准备服务器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1%E3%80%81%E5%88%9B%E5%BB%BAserver-order0%E5%AE%B9%E5%99%A8"><span class="toc-text">1.1、创建server-order0容器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2%E3%80%81%E5%88%9B%E5%BB%BAserver-order1%E5%AE%B9%E5%99%A8"><span class="toc-text">1.2、创建server-order1容器</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E5%9F%BA%E6%9C%AC%E6%B0%B4%E5%B9%B3%E5%88%86%E7%89%87"><span class="toc-text">2、基本水平分片</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1%E3%80%81%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE"><span class="toc-text">2.1、基本配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2%E3%80%81%E6%95%B0%E6%8D%AE%E6%BA%90%E9%85%8D%E7%BD%AE"><span class="toc-text">2.2、数据源配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3%E3%80%81%E6%A0%87%E6%A4%8E%E5%88%86%E7%89%87%E8%A1%A8%E9%85%8D%E7%BD%AE"><span class="toc-text">2.3、标椎分片表配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4%E3%80%81%E8%A1%8C%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-text">2.4、行表达式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-5%E3%80%81%E5%88%86%E7%89%87%E7%AE%97%E6%B3%95%E9%85%8D%E7%BD%AE"><span class="toc-text">2.5、分片算法配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-6%E3%80%81%E5%88%86%E5%B8%83%E5%BC%8F%E5%BA%8F%E5%88%97%E7%AE%97%E6%B3%95"><span class="toc-text">2.6、分布式序列算法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E5%A4%9A%E8%A1%A8%E5%85%B3%E8%81%94"><span class="toc-text">3、多表关联</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1%E3%80%81%E5%88%9B%E5%BB%BA%E5%85%B3%E8%81%94%E8%A1%A8"><span class="toc-text">3.1、创建关联表</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2%E3%80%81%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BD%93%E7%B1%BB"><span class="toc-text">3.2、创建实体类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3%E3%80%81%E5%88%9B%E5%BB%BAMapper"><span class="toc-text">3.3、创建Mapper</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-4%E3%80%81%E9%85%8D%E7%BD%AE%E5%85%B3%E8%81%94%E8%A1%A8"><span class="toc-text">3.4、配置关联表</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-5%E3%80%81%E6%B5%8B%E8%AF%95%E6%8F%92%E5%85%A5%E6%95%B0%E6%8D%AE"><span class="toc-text">3.5、测试插入数据</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E7%BB%91%E5%AE%9A%E8%A1%A8"><span class="toc-text">4、绑定表</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1%E3%80%81%E5%88%9B%E5%BB%BAVO%E5%AF%B9%E8%B1%A1"><span class="toc-text">4.1、创建VO对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2%E3%80%81%E6%B7%BB%E5%8A%A0Mapper%E6%96%B9%E6%B3%95"><span class="toc-text">4.2、添加Mapper方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3%E3%80%81%E6%B5%8B%E8%AF%95%E5%85%B3%E8%81%94%E6%9F%A5%E8%AF%A2"><span class="toc-text">4.3、测试关联查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4%E3%80%81%E9%85%8D%E7%BD%AE%E7%BB%91%E5%AE%9A%E8%A1%A8"><span class="toc-text">4.4、配置绑定表</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5%E3%80%81%E5%B9%BF%E6%92%AD%E8%A1%A8"><span class="toc-text">5、广播表</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1%E3%80%81%E4%BB%80%E4%B9%88%E6%98%AF%E5%B9%BF%E6%92%AD%E8%A1%A8"><span class="toc-text">4.1、什么是广播表</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2%E3%80%81%E5%88%9B%E5%BB%BA%E5%B9%BF%E6%92%AD%E8%A1%A8"><span class="toc-text">4.2、创建广播表</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3%E3%80%81%E7%A8%8B%E5%BA%8F%E5%AE%9E%E7%8E%B0"><span class="toc-text">4.3、程序实现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#4-3-1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BD%93%E7%B1%BB"><span class="toc-text">4.3.1、创建实体类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-3-2%E3%80%81%E5%88%9B%E5%BB%BAMapper"><span class="toc-text">4.3.2、创建Mapper</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-3-3%E3%80%81%E9%85%8D%E7%BD%AE%E5%B9%BF%E6%92%AD%E8%A1%A8"><span class="toc-text">4.3.3、配置广播表</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4%E3%80%81%E6%B5%8B%E8%AF%95%E5%B9%BF%E6%92%AD%E8%A1%A8"><span class="toc-text">4.4、测试广播表</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC07%E7%AB%A0-%E5%90%AF%E5%8A%A8ShardingSphere-Proxy"><span class="toc-text">第07章 启动ShardingSphere-Proxy</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E8%8E%B7%E5%8F%96"><span class="toc-text">1、获取</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E4%BD%BF%E7%94%A8%E4%BA%8C%E8%BF%9B%E5%88%B6%E5%8F%91%E5%B8%83%E5%8C%85%E5%AE%89%E8%A3%85"><span class="toc-text">2、使用二进制发布包安装</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E4%BD%BF%E7%94%A8Docker%E5%AE%89%E8%A3%85"><span class="toc-text">3、使用Docker安装</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC08%E7%AB%A0-ShardingSphere-Proxy%E8%AF%BB%E5%86%99%E5%88%86%E7%A6%BB"><span class="toc-text">第08章 ShardingSphere-Proxy读写分离</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E4%BF%AE%E6%94%B9%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-text">1、修改配置文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E5%AE%9E%E6%97%B6%E6%9F%A5%E7%9C%8B%E6%97%A5%E5%BF%97"><span class="toc-text">2、实时查看日志</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E8%BF%9C%E7%A8%8B%E8%AE%BF%E9%97%AE%E6%B5%8B%E8%AF%95"><span class="toc-text">3、远程访问测试</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E5%BA%94%E7%94%A8%E7%A8%8B%E5%BA%8F%E8%AE%BF%E9%97%AEProxy"><span class="toc-text">4、应用程序访问Proxy</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1%E3%80%81%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE"><span class="toc-text">4.1、创建项目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2%E3%80%81%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96"><span class="toc-text">4.2、添加依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3%E3%80%81%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BD%93%E7%B1%BB"><span class="toc-text">4.3、创建实体类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4%E3%80%81%E5%88%9B%E5%BB%BAMapper"><span class="toc-text">4.4、创建Mapper</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-5%E3%80%81%E9%85%8D%E7%BD%AE%E6%95%B0%E6%8D%AE%E6%BA%90"><span class="toc-text">4.5、配置数据源</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-6%E3%80%81%E6%B5%8B%E8%AF%95"><span class="toc-text">4.6、测试</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC09%E7%AB%A0-ShardingSphere-Proxy%E5%9E%82%E7%9B%B4%E5%88%86%E7%89%87"><span class="toc-text">第09章 ShardingSphere-Proxy垂直分片</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E4%BF%AE%E6%94%B9%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6-1"><span class="toc-text">1、修改配置文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E5%AE%9E%E6%97%B6%E6%9F%A5%E7%9C%8B%E6%97%A5%E5%BF%97-1"><span class="toc-text">2、实时查看日志</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E8%BF%9C%E7%A8%8B%E8%AE%BF%E9%97%AE%E6%B5%8B%E8%AF%95-1"><span class="toc-text">3、远程访问测试</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC10%E7%AB%A0-ShardingSphere-Proxy%E6%B0%B4%E5%B9%B3%E5%88%86%E7%89%87"><span class="toc-text">第10章 ShardingSphere-Proxy水平分片</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E4%BF%AE%E6%94%B9%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6-2"><span class="toc-text">1、修改配置文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E5%AE%9E%E6%97%B6%E6%9F%A5%E7%9C%8B%E6%97%A5%E5%BF%97-2"><span class="toc-text">2、实时查看日志</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E8%BF%9C%E7%A8%8B%E8%AE%BF%E9%97%AE%E6%B5%8B%E8%AF%95-2"><span class="toc-text">3、远程访问测试</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer" style="background-color: transparent;"><div id="footer-wrap"><div id="ft"><div class="ft-item-1"><div class="t-top"><div class="t-t-l"><p class="ft-t t-l-t">格言🧬</p><div class="bg-ad"><div>再看看那个光点，它就在这里，这是家园，这是我们 —— 你所爱的每一个人，你认识的一个人，你听说过的每一个人，曾经有过的每一个人，都在它上面度过他们的一生✨</div><div class="btn-xz-box"><a class="btn-xz" target="_blank" rel="noopener" href="https://stellarium.org/">点击开启星辰之旅</a></div></div></div><div class="t-t-r"><p class="ft-t t-l-t">猜你想看💡</p><ul class="ft-links"><li><a href="/posts/eec9786.html">魔改指南</a><a href="/box/nav/">网址导航</a></li><li><a href="/social/link/">我的朋友</a><a href="/comments/">留点什么</a></li><li><a href="/personal/about/">关于作者</a><a href="/archives/">文章归档</a></li><li><a href="/categories/">文章分类</a><a href="/tags/">文章标签</a></li><li><a href="/box/Gallery/">我的画廊</a><a href="/personal/bb/">我的唠叨</a></li><li><a href="/site/time/">建设进程</a><a href="/site/census/">网站统计</a></li></ul></div></div></div><div class="ft-item-2"><p class="ft-t">推荐友链⌛</p><div class="ft-img-group"><div class="img-group-item"><a href="https://www.naste.top:1024/" title="XiaoFei🥝"><img src= "" data-lazy-src="https://www.naste.top:9000/images/cat.jpg" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div></div></div></div><div class="copyright"><span><b>&copy;2022-2024</b></span><span><b>&nbsp;&nbsp;By XiaoFei🥝</b></span></div><div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" title="博客框架为Hexo_v6.3.0"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Frame-Hexo-blue.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" style="margin-inline:5px" title="主题版本Butterfly_v4.3.1"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Theme-Butterfly-6513df.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://vercel.com/" style="margin-inline:5px" title="本站采用多线部署，主线路托管于Vercel"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Hosted-Vercel-brightgreen.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://user.51.la/" style="margin-inline:5px" title="本站数据分析得益于51la技术支持"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Analytics-51la-3db1eb.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://github.com/" style="margin-inline:5px" title="本网站源码由Github提供存储仓库"><img src= "" data-lazy-src=" https://static.naste.top:1024/svg/blog/Source-Github-d021d6.svg" alt=""/></a></p></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><a class="icon-V hidden" onclick="switchNightMode()" title="浅色和深色模式转换"><svg width="25" height="25" viewBox="0 0 1024 1024"><use id="modeicon" xlink:href="#icon-moon"></use></svg></a><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button><button class="share" type="button" title="右键模式" onclick="changeMouseMode()"><i class="fas fa-mouse"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog right_side"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button class="share" type="button" title="分享链接" onclick="share()"><i class="fas fa-share-nodes"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i><span id="percent">0<span>%</span></span></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div class="js-pjax" id="rightMenu"><div class="rightMenu-group rightMenu-small"><a class="rightMenu-item" href="javascript:window.history.back();"><i class="fa fa-arrow-left"></i></a><a class="rightMenu-item" href="javascript:window.history.forward();"><i class="fa fa-arrow-right"></i></a><a class="rightMenu-item" href="javascript:window.location.reload();"><i class="fa fa-refresh"></i></a><a class="rightMenu-item" href="javascript:rmf.scrollToTop();"><i class="fa fa-arrow-up"></i></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-text"><a class="rightMenu-item" href="javascript:rmf.copySelect();"><i class="fa fa-copy"></i><span>复制</span></a><a class="rightMenu-item" href="javascript:window.open(&quot;https://www.baidu.com/s?wd=&quot;+window.getSelection().toString());window.location.reload();"><i class="fa fa-search"></i><span>百度搜索</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-too"><a class="rightMenu-item" href="javascript:window.open(window.getSelection().toString());window.location.reload();"><i class="fa fa-link"></i><span>转到链接</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-paste"><a class="rightMenu-item" href="javascript:rmf.paste()"><i class="fa fa-copy"></i><span>粘贴</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-post"><a class="rightMenu-item" href="#post-comment"><i class="fas fa-comment"></i><span>空降评论</span></a><a class="rightMenu-item" href="javascript:rmf.copyWordsLink()"><i class="fa fa-link"></i><span>复制本文地址</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-to"><a class="rightMenu-item" href="javascript:rmf.openWithNewTab()"><i class="fa fa-window-restore"></i><span>新窗口打开</span></a><a class="rightMenu-item" id="menu-too" href="javascript:rmf.open()"><i class="fa fa-link"></i><span>转到链接</span></a><a class="rightMenu-item" href="javascript:rmf.copyLink()"><i class="fa fa-copy"></i><span>复制链接</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-img"><a class="rightMenu-item" href="javascript:rmf.saveAs()"><i class="fa fa-download"></i><span>保存图片</span></a><a class="rightMenu-item" href="javascript:rmf.openWithNewTab()"><i class="fa fa-window-restore"></i><span>在新窗口打开</span></a><a class="rightMenu-item" href="javascript:rmf.copyLink()"><i class="fa fa-copy"></i><span>复制图片链接</span></a></div><div class="rightMenu-group rightMenu-line"><a class="rightMenu-item" href="javascript:randomPost()"><i class="fa fa-paper-plane"></i><span>随便逛逛</span></a><a class="rightMenu-item" href="javascript:switchNightMode();"><i class="fa fa-moon"></i><span>昼夜切换</span></a><a class="rightMenu-item" href="/personal/about/"><i class="fa fa-info-circle"></i><span>关于博客</span></a><a class="rightMenu-item" href="javascript:toggleWinbox();"><i class="fas fa-cog"></i><span>美化设置</span></a><a class="rightMenu-item" href="javascript:rmf.fullScreen();"><i class="fas fa-expand"></i><span>切换全屏</span></a><a class="rightMenu-item" href="javascript:window.print();"><i class="fa-solid fa-print"></i><span>打印页面</span></a></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.umd.min.js"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/instant.page/5.1.0/instantpage.min.js" type="module"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/vanilla-lazyload/17.3.1/lazyload.iife.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdnjs.cloudflare.com/ajax/libs/pangu/4.0.7/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (true){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><script async="async">var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())
setTimeout(function(){preloader.endLoading();}, 5000);
document.getElementById('loading-box').addEventListener('click',()=> {preloader.endLoading()})</script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.min.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: '',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      }
    }, null))
  }

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: '',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      countELement.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.staticfile.org/twikoo/1.6.8/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script src="https://cdn.staticfile.org/jquery/3.6.3/jquery.min.js"></script><script async src="https://cdn1.tianli0.top/npm/vue@2.6.14/dist/vue.min.js"></script><script async src="https://cdn1.tianli0.top/npm/element-ui@2.15.6/lib/index.js"></script><script async src="https://cdn.bootcdn.net/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script><script defer type="text/javascript" src="https://cdn1.tianli0.top/npm/sweetalert2@8.19.0/dist/sweetalert2.all.js"></script><script async src="//npm.elemecdn.com/pace-js@1.2.4/pace.min.js"></script><script defer src="https://cdn1.tianli0.top/gh/nextapps-de/winbox/dist/winbox.bundle.min.js"></script><script async src="//at.alicdn.com/t/c/font_3586335_hsivh70x0fm.js"></script><script async src="//at.alicdn.com/t/c/font_3636804_gr02jmjr3y9.js"></script><script async src="//at.alicdn.com/t/c/font_3612150_kfv55xn3u2g.js"></script><script async src="https://cdn.wpon.cn/2022-sucai/Gold-ingot.js"></script><canvas id="universe"></canvas><canvas id="snow"></canvas><script defer src="/js/fomal.js"></script><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/aplayer/1.10.1/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/aplayer/1.10.1/APlayer.min.js"></script><script src="https://cdn1.tianli0.top/npm/js-heo@1.0.12/metingjs/Meting.min.js"></script><script src="https://lib.baomitu.com/pjax/0.2.8/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show","#web_bg",".js-pjax","#bibi","body > title","#app","#tag-echarts","#posts-echart","#categories-echarts"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --> <script data-pjax>if(document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    var parent = document.getElementById('recent-posts');
    var child = '<div class="recent-post-item" style="width:100%;height: auto"><div id="catalog_magnet"><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Java/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍡 XiaoFeiのJava学习笔记 (55)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Linux/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍼 XiaoFeiのLinux笔记 (33)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Python/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍉 XiaoFeiのPython笔记 (2)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/前端/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍟 XiaoFeiの前端笔记 (17)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Other/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍥 XiaoFeiのOther笔记 (10)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item" style="visibility: hidden"></div><a class="magnet_link_more"  href="https://www.naste.top:1024/categories/" style="flex:1;text-align: center;margin-bottom: 10px;">查看更多...</a></div></div>';
    console.log('已挂载magnet')
    parent.insertAdjacentHTML("afterbegin",child)}
     </script><style>#catalog_magnet{flex-wrap: wrap;display: flex;width:100%;justify-content:space-between;padding: 10px 10px 0 10px;align-content: flex-start;}.magnet_item{flex-basis: calc(33.333333333333336% - 5px);background: #e9e9e9;margin-bottom: 10px;border-radius: 8px;transition: all 0.2s ease-in-out;}.magnet_item:hover{background: var(--text-bg-hover)}.magnet_link_more{color:#555}.magnet_link{color:black}.magnet_link:hover{color:white}@media screen and (max-width: 600px) {.magnet_item {flex-basis: 100%;}}.magnet_link_context{display:flex;padding: 10px;font-size:16px;transition: all 0.2s ease-in-out;}.magnet_link_context:hover{padding: 10px 20px;}</style>
    <style></style><script data-pjax>
  function butterfly_swiper_injector_config(){
    var parent_div_git = document.getElementById('recent-posts');
    var item_html = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms;"><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912191.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2023-03-08</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt="">SpringBoot使用实现定时任务和xxl-job实现分布式任务调度</a><div class="blog-slider__text">SpringBoot使用实现定时任务和xxl-job实现分布式任务调度</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678672933.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2023-03-15</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt="">Hexo中Markdown语法与外挂标签写法汇总</a><div class="blog-slider__text">Hexo中Markdown语法与外挂标签写法汇总</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载butterfly_swiper')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'undefined'.split(',');
  var cpage = location.pathname;
  var epage = '/';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_swiper_injector_config();
  }
  else if (epage === cpage){
    butterfly_swiper_injector_config();
  }
  </script><script defer src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper_init.js"></script><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '30');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '30');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script></div><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow.min.js"></script><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow_init.js"></script><script data-pjax src="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.js"></script><script data-pjax>
  function gitcalendar_injector_config(){
      var parent_div_git = document.getElementById('gitZone');
      var item_html = '<div class="recent-post-item" id="gitcalendarBar" style="width:100%;height:auto;padding:10px;"><style>#git_container{min-height: 320px}@media screen and (max-width:650px) {#git_container{min-height: 0px}}</style><div id="git_loading" style="width:10%;height:100%;margin:0 auto;display: block;"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50" xml:space="preserve"><path fill="#d0d0d0" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z" transform="rotate(275.098 25 25)"><animatetransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.6s" repeatCount="indefinite"></animatetransform></path></svg><style>#git_container{display: none;}</style></div><div id="git_container"></div></div>';
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      console.log('已挂载gitcalendar')
      }

    if( document.getElementById('gitZone') && (location.pathname ==='/personal/about/'|| '/personal/about/' ==='all')){
        gitcalendar_injector_config()
        GitCalendarInit("https://gitcalendar.naste.top/api?xiao-i-fei",['#d9e0df', '#c6e0dc', '#a8dcd4', '#9adcd2', '#89ded1', '#77e0d0', '#5fdecb', '#47dcc6', '#39dcc3', '#1fdabe', '#00dab9'],'xiao-i-fei')
    }
  </script><!-- hexo injector body_end end --></body></html>